get_posts或wp_query函数中的Foreach问题

问题描述 投票:0回答:2

我的类别来自逗号分隔的地方,然后将其放入wp_query的args数组中,但是我的查询只给我最后一个类别的帖子。请在下面查看我的代码:

$content_arr = explode(",", $content);

  if ( is_array($content_arr) && count($content_arr) > 0 ) {
    foreach ($content_arr as $category_name) { // Category loop
      $args = array(
        'category_name'  => trim($category_name),
        'posts_per_page' => 7,
        'order'          => 'DESC',
        'orderby'        => 'post_date',
      );

      $output = '';      
      // $posts = get_posts($args);
      $post_counter = 1;

      $the_query = new WP_Query( $args );

      if ( $the_query->have_posts() ) : 
        while ( $the_query->have_posts() ) : $the_query->the_post(); 
            if ( has_post_thumbnail() ):
              //the_post_thumbnail();
            else: 

            endif;
            $output .= '<div class="col-md-4 mb-5">'.get_the_ID().'-'.get_the_title().'</div>';
            $post_counter++;
        endwhile; 
        $the_query->reset_postdata();
        echo $post_counter."-";
      endif;
    ```
In **$content_arr** have 3 category as array element so first foreach is running 3 times but my output is showing only one category posts.
Somehow it is resetting my previous category's results.
How can i show my all categories posts one by one?
Thanks.
wordpress categories posts
2个回答
0
投票

如果要在$output循环外打印变量foreach,请在循环外定义$output= '';,这可能会有所帮助,可能会重置您的结果并仅显示最后一个循环结果

**确保您将类别标签传递给WP_Query

希望这可以帮助您跟踪代码


0
投票

实际上,我在第11行犯了一个逻辑错误。它不应以字符串开头,$ output ='';谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.