这可能是一个完全“我对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()
我还不明白。