如何使用array_filter按帖子的类别对其分组? 类别“ 1935” 类别“ 1936”

问题描述

我有一个名为 cpt-magazines 的自定义帖子类型,以及一个名为 ctax-publication-year 的自定义分类法em>。在我的模板文件中,我想使用array_filter()按帖子的类别对帖子进行分组(所有帖子仅为其分配了一个类别),从“高级自定义字段”中获取一些元数据,并按照其顺序输出帖子标题。

最终结果目标:

类别“ 1935”

1935年第一期杂志

1935年第2号杂志

类别“ 1936”

1936年第一杂志

1936年第2号杂志

...等等。

目前,这是我所得到的代码(请注意,$ iteration仅在我确定代码时限制输出):

<section class="section-magazines has-padding">
  <div class="container">
    <div class="row">
            
      <?php
      // Get categories
      $getTerms = get_terms( array(
        'taxonomy'    => 'ctax-publication-year','orderby'     => 'title','order'       => 'ASC','hide_empty'  => false
      ) );

      // Query arguments
      $queryArgs = array(
        'post_type'        => 'cpt-magazines','posts_per_page'   => '-1',);

      $postsQuery = new WP_Query( $queryArgs );
      $postsArray = $postsQuery->posts;
      ?>
            
      <div class="col-12">
        <?php
        $iteration = 1;
        
        foreach ( $getTerms as $term ) {
        
          // Limit to 2 categories while testing
          if ( $iteration > 2 ) {
            break;
          }
          
          echo "<h2>". $term->name ."</h2>";
        
          $postsInCategory = array_filter( $postsArray,function($post) {
            return $post->term_id == $term->term_id;
          } );
        
          var_dump($postsInCategory);
        
          $iteration++;
        }
        ?>
      </div>
            
    </div>
  </div>
</section>

到目前为止,我已经能够打印出H2标签内的所有类别名称,所以我觉得我已经把这部分记下来了。我现在想弄清楚的是如何过滤具有每个类别循环类别的帖子,以及如何从每个帖子中获取元数据。 我的代码现在输出一个251个项目的数组(这是自定义帖子类型的帖子的总数)以及每个项目的一些数据,看起来像这样(我剪短了,因为它非常长数组,当然):

array(251) { 
  [0]=> object(WP_Post)#8876 (24) { 
    ["ID"]=> int(9250) 
    ["post_author"]=> string(1) "1" 
    ["post_date"]=> string(19) "2020-08-07 12:04:14" 
    ["post_date_gmt"]=> string(19) "2020-08-07 10:04:14" 
    ["post_content"]=> string(0) "" 
    ["post_title"]=> string(14) "Tegel #1,1987" 
    ["post_excerpt"]=> string(0) "" 
    ["post_status"]=> string(7) "publish" 
    ["comment_status"]=> string(6) "closed" 
    ["ping_status"]=> string(6) "closed" 
    ["post_password"]=> string(0) "" 
    ["post_name"]=> string(12) "tegel-1-1987" 
    ["to_ping"]=> string(0) "" 
    ["pinged"]=> string(0) "" 
    ["post_modified"]=> string(19) "2020-08-07 12:04:14" 
    ["post_modified_gmt"]=> string(19) "2020-08-07 10:04:14" 
    ["post_content_filtered"]=> string(0) "" 
    ["post_parent"]=> int(0) 
    ["guid"]=> string(52) "http://spef:8888/?post_type=cpt-magazines&p=9250" 
    ["menu_order"]=> int(0) 
    ["post_type"]=> string(13) "cpt-magazines" 
    ["post_mime_type"]=> string(0) "" 
    ["comment_count"]=> string(1) "0" 
    ["filter"]=> string(3) "raw" 
}

我认为我模糊地理解了array_filter()函数的工作原理,但是我不太了解如何检索/使用其中的数据。

在此先感谢您的帮助!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)