借助WP_Query获取所有帖子

时间:2019-02-03 10:17:33

标签: wordpress

我需要获取网站的所有帖子。我尝试在部件中完成该操作,但结果还是空的。

global $post;

$args = array(
  'post_type' => 'post',
  'post_status' => 'publish'
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
  while ($query->have_posts()) {
    $query->the_post();
    var_dump($post->ID);
  }
}

当我在参数数组参数cat中添加然后返回帖子时,但是我需要从所有类别中获取所有帖子,而不仅仅是从指定类别中获取。

$args = array(
  'post_type' => 'post',
  'post_status' => 'publish',
  'cat' => 22
);

4 个答案:

答案 0 :(得分:0)

确保global $post在相同的功能/范围内。

如果仍然无法运行,请尝试使用{p> 1代替

var_dump($post->ID)

也不要忘记在var_dump($query->post->ID) 循环之后调用wp_reset_postdata()

答案 1 :(得分:0)

尝试一下:

$args = array(
            'post_type' => 'post',
            'posts_per_page' => -1
        );
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
        the_title();
        the_content();
    endwhile;
    wp_reset_postdata();
endif;

答案 2 :(得分:0)

posts_per_page 设置为 -1 ,这将返回数据库中的所有帖子。

$args = array(
    'posts_per_page'   => -1,
    'post_type'        => 'post',
);
$the_query = new WP_Query( $args );

while ( $the_query->have_posts() ) {
  // do stuff
}

答案 3 :(得分:0)

我了解问题所在,在现场(我目前工作的地方)安装了polylang,当我在参数get_posts中为函数'lang' => pll_current_language()指定时,它将返回当前语言的所有帖子。

$results = get_posts(
  array(
    'numberposts' => 9999,
    'orderby'     => 'rand',
    'order'       => 'ASC',
    'post_type'   => 'post',
    'post_status' => 'publish',
    'lang'        => pll_current_language()
  )
);
相关问题