使用SETUP_POSTData()时出错

时间:2015-10-05 作者:Louis W

我正在尝试获取最新的,并使用本机函数(例如get\\u the\\u title())显示它,不想使用$post[\'post\\u title\',但当我这样做时,我是一个错误。

global $post;

$featured_post = wp_get_recent_posts(array( \'numberposts\'=>\'1\', \'post_type\' => \'post\' ));

foreach ($featured_post as $post) {

    setup_postdata($post);  

    echo get_the_title();

}
这就是我得到的错误:

Notice: Trying to get property of non-object in /.../wp-includes/query.php on line 4601
Notice: Trying to get property of non-object in /.../wp-includes/query.php on line 4603
Notice: Trying to get property of non-object in /.../wp-includes/query.php on line 4605
Notice: Trying to get property of non-object in /.../wp-includes/query.php on line 4606
Notice: Trying to get property of non-object in /.../wp-includes/query.php on line 4617
Notice: Trying to get property of non-object in /.../wp-includes/query.php on line 4625
Notice: Trying to get property of non-object in /.../wp-includes/query.php on line 4642

1 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

您收到错误是因为默认情况下,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

相关推荐

如何读取WordPress$Query关联数组(散列)键的值

WordPress编程新手(来自更为传统的环境),并试图了解其一些“独特”特性。我们的网站上有一个目录页,此代码驻留在functions.php, 如果条件为true,则调整结果。if( $query->is_post_type_archive( \'directory\' ) ){ ...//do stuff } 我想知道如何获取is_post_type_archive 这就是“目录”当我对值使用测试时。。。var_dumb($query->is_post