Wordpress: include content of one page in another
Pages are just posts, with a post_type of 'page' in the database. You can show the content of multiple pages on another page by writing a post query in your pageX template that gets the posts you specify and output them in a Loop.
There are three ways to get post content from the database:
- get_posts
- query_posts
- WP_Query
These links all point to the WordPress Codex. Get_posts and query_posts have an argument available, 'page_id', where you can specify the id of the page you'd like to retrieve and display.
I found this answer posted on the Wordpress forums. You add a little code to functions.php and then just use a shortcode whenever you like.
function get_post_page_content( $atts ) {
extract( shortcode_atts( array(
'id' => null,
'title' => false,
), $atts ) );
$the_query = new WP_Query( 'page_id='.$id );
while ( $the_query->have_posts() ) {
$the_query->the_post();
if($title == true){
the_title();
}
the_content();
}
wp_reset_postdata();
}
add_shortcode( 'my_content', 'get_post_page_content' );
For the shortcode,
[my_content id="Enter your page id number" title=Set this to true if you want to show title /]
There is not a show_post()
function per se in WordPress core but it is extremely easy to write:
function show_post($path) {
$post = get_page_by_path($path);
$content = apply_filters('the_content', $post->post_content);
echo $content;
}
Note that this would be called with the page's path, i.e.:
<?php show_post('about'); // Shows the content of the "About" page. ?>
<?php show_post('products/widget1'); // Shows content of the "Products > Widget" page. ?>
Of course I probably wouldn't name a function as generically as show_post()
in case WordPress core adds a same-named function in the future. Your choice though.
Also, and no slight meant to @kevtrout because I know he is very good, consider posting your WordPress questions on StackOverflow's sister site WordPress Answers in the future. There's a much higher percentage of WordPress enthusiasts answering questions over there.