如何解决如何使用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 举报,一经查实,本站将立刻删除。