WP_Query-> post_name返回null

时间:2015-04-09 22:14:36

标签: php wordpress wp-query

我试图从wordpress中的WP_Query($args)函数获取post_name属性。如果我使用var_dump($wp_query);,则会向我显示post_name属性不为空或为空。这是帖子的标题。

但如果我试图使用echo $wp_query->post_name;回复它,则会返回一个空字符串。

这是我定义$wp_query

的方式
$args = array('posts_per_page' => 5, 'tag' => 'General');
$wp_query = new WP_Query( $args );

有些帖子标有" General"所以这不是原因。

有人可以解释一下这种行为或告诉我我做错了什么吗?

3 个答案:

答案 0 :(得分:1)

这是因为$wp_query不是单个帖子,而是与查询匹配的所有帖子。这意味着您必须以某种方式遍历查询结果中的帖子。例如,你可以这样做:

$args = array('posts_per_page' => 5, 'tag' => 'General');
$wp_query = new WP_Query( $args );

// Get the posts from the query
$posts = $wp_query->get_posts();

// Loop through the posts
foreach( $posts as $post ) {
    echo $post->post_name;
}

答案 1 :(得分:0)

$args = array('posts_per_page' => 5, 'tag' => 'General');

// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

参考:WP_Query

答案 2 :(得分:0)

post_namepost_title是两回事。

post_title是帖子的标题,而post_name是帖子在固定链接中的独特部分 - 也称为slug。

而不是使用

echo $wp_query->post_name;

使用:

echo $wp_query->post_title;
相关问题