Wordpress: include content of one page in another

2019-01-31 12:28发布

How do I include the page content of one or more page in another page?

ex. I have pageA, pageB and pageC and I want to include the contents of these pages in pageX

is there a wordpress function that loads the post of a specified page/post?
like show_post("pageA")??

标签: php wordpress
8条回答
Deceive 欺骗
2楼-- · 2019-01-31 13:32

Hi @dany:

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.

Hope this helps.

-Mike

查看更多
forever°为你锁心
3楼-- · 2019-01-31 13:34

Kit Johnson's wordpress forum solution with creating a shortcode works, but adds the inserted page in the top of the new page, not where the shortcode was added. Close though, and may work for other people.

from the wordpress post, I pieced together this which inserts the page where the shortcode is put:

function get_post_page_content( $atts ) {
    extract( shortcode_atts( array(
        'id' => null,
        'title' => false,
    ), $atts ) );
    $output = "";       

    $the_query = new WP_Query( 'page_id='.$id );
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
            if($title == true){
            $output .= get_the_title();
            }
            $output .= get_the_content();
    }
    wp_reset_postdata();
    return $output;

}

Then, the shortcode bit works as expected. If you don't want the title, title=false does not work, you need to leave title off entirely.

查看更多
登录 后发表回答