如何使用此代码输出页面内容?

时间:2015-01-21 作者:wilsonf1

我在stackoverflow上找到了这段代码,但我如何输出实际内容,而不仅仅是示例中的ID行!

<?php
        $the_slug = \'my-page\';
        $args=array(
        \'name\' => $the_slug,
        \'post_type\' => \'page\',
        \'post_status\' => \'publish\',
        \'numberposts\' => 1
        );
        $my_posts = get_posts($args);
        if( $my_posts ) {
            echo \'ID on the first post found \'.$my_posts[0]->ID; the_content();
        }
        ?>

2 个回复
最合适的回答,由SO网友:Nathan Fitzgerald - Fitzgenius 整理而成

这是WordPress主查询之外的“自定义”循环(query_posts), 您必须告诉WordPress使用setup_postdata()

有关的详细信息get_posts() 在这里可以找到,基本上给你我下面要写的内容:http://codex.wordpress.org/Template_Tags/get_posts

提示:除了谷歌,WordPress Codex是你最好的朋友。

<?php

$the_slug = \'my-page\';

$args = array(
    \'name\'          => $the_slug,
    \'post_type\'     => \'page\',
    \'post_status\'   => \'publish\',
    \'numberposts\'   => 1
);

$my_posts = get_posts($args);

if( $my_posts ) {

    echo \'ID on the first post found \'.$my_posts[0]->ID;

    // To get the content of the first post:
    echo apply_filters(\'the_content\', $my_posts[0]->post_content);

    // if you now wanted to remove the first post from this loop and assign it to a different variable $first_post
    // However, it looks as if you are only grabbing one "post" being a "page" from the slug "my-page"
    $first_post = $my_posts[0];
    unset($my_posts[0]);

    foreach($my_posts as $p): setup_postdata($p); 

        // Now you can use the_title(), the_content() etc as you normally would

    endforeach;

}

// Reset WordPress Loop & WP_Query
wp_reset_postdata();

?>

SO网友:Михаил Семёнов

$my_posts[0]->post_content

要获得正确的外观,您需要应用过滤器the_content 并进行一些更换(如the_content() 确实如此)

str_replace( \']]>\', \']]&gt;\', apply_filters(\'the_content\', $my_posts[0]->post_content ) );

如果你想经常使用它,我建议你做你自己的功能:

function my_get_content( $content ) { return str_replace( \']]>\', \']]&gt;\', apply_filters(\'the_content\', $content ) );

然后这样称呼它:echo my_get_content( $my_posts[0]->post_content );

结束

相关推荐