您收到错误是因为默认情况下,wp_get_recent_posts 返回一个post数组(由于向后兼容),而不是必需的WP_Post 设置模板标记所需的对象。
看看源代码,你会看到wp_get_recent_posts 是一个简单的包装函数get_posts (这只是WP_Query)。是什么导致了wp_get_recent_posts, 是它的第二个参数的值,$output 默认设置为ARRAY_A. 默认情况下get_posts 转换为数组。下面是负责这一点的代码。
// Backward compatibility. Prior to 3.1 expected posts to be returned in array.
if ( ARRAY_A == $output ){
foreach( $results as $key => $result ) {
$results[$key] = get_object_vars( $result );
}
return $results ? $results : array();
}
要使代码正常工作,只需向
wp_get_recent_posts 将返回
WP_Post 对象直接来自
get_posts$featured_post = wp_get_recent_posts(array( \'numberposts\'=>\'1\', \'post_type\' => \'post\' ), \'\');
或者,就此而言
$featured_post = wp_get_recent_posts(array( \'numberposts\'=>\'1\', \'post_type\' => \'post\' ), \'CRAP\');
最后,简单地使用
the_title() 要显示标题,无需
echo get_the_title()编辑别忘了打电话wp_reset_postdata() 在您的foreach 环