这可能是一个完全“我对WP还是新手”类型的问题,但在使用get_posts() 和wp_get_recent_posts() 在我编写的自定义函数中setup_postdata(). 这是我的函数中的内容。php文件:
<?php
function getRecentPosts($total_posts = 2)
{
    $total_posts = intval($total_posts);
    global $post;
    $args = array(
        \'posts_per_page\' => $total_posts,
        \'post_type\'      => \'post\',
        \'post_status\'    => \'publish\'
    );
    $posts = get_posts($args);
    foreach ($posts as $post)
    {
        setup_postdata($post);
        echo \'<div>\';
            the_title();
        echo \'</div>\';
    }
    wp_reset_postdata();
}
 很简单,对吧?这个功能非常有效,去掉了标题的内部
div 标签完美无瑕。但当我将第7-12行替换为以下内容时:
    ...
    $args = array(
        \'posts_per_page\' => $total_posts,
        //\'post_type\'    => \'post\',
        \'post_status\'    => \'publish\'
    );
    $posts = wp_get_recent_posts($args);
    ...
 。。。然后,该函数似乎无法正确地“迭代”帖子,反复抛出它找到的第一篇帖子的标题,就像不使用
global $post 在函数的开头。
为什么会这样?有什么不同的地方wp_get_recent_posts() 我还不明白。
 
                    最合适的回答,由SO网友:Stephen Harris 整理而成
                    如果你看看source 属于setup_postdata() 你会发现它需要一个对象($post), 要传递,而不是数组。
wp_get_recent_posts() (source), 默认情况下(对于3.1之前的向后兼容性),将每个帖子作为数组返回。第二个可选参数,可以传递给wp_get_recent_posts() 可以防止这种情况:
$posts = wp_get_recent_posts( $args, OBJECT_K )
(尽管任何值
ARRAY_A 在第二个参数中)。