问题描述
在作者档案页面上,我想显示作者在其中发布帖子(在我的情况下为WooCommerce产品)的每种分类法(在我的情况下为产品类别)。
为此,我正在使用以下代码:
$posts = get_posts( array('post_type' => 'product','posts_per_page' => -1,'author' => $author_id) );
$author_categories = array();
//loop over the posts and collect the terms
foreach ($posts as $p) {
$author_categories = wp_get_object_terms( $p->ID,'product_cat');
if ( ! empty( $author_categories ) && ! is_wp_error( $author_categories ) ){
echo '<div class="d-flex flex-wrap">';
foreach ($author_categories as $author_category) {
//var_dump($t);
$author_category_link = get_term_link( $author_category );
$author_category_name = $author_categories[] = $author_category->name;
echo '<a href="'.esc_url( $author_category_link ).'" class="p-2 p-lg-5 bg-light text-center">';
echo $author_category_name;
echo '</a>';
}
echo '</div>';
}
}
wp_reset_postdata();
问题是产品类别出现了多次。我猜该产品类别中的每条帖子。
有什么办法可以首先收集术语并仅按产品类别中的帖子数排序显示它们?
解决方法
您应该首先将所有类别收集在容器数组中。在将类别添加到阵列时,通过使用类别的ID或名称作为阵列键,可以消除重复项。然后,您只需遍历结果数组即可回显类别。
// First just collect the distinct categories.
$posts = get_posts( array('post_type' => 'product','posts_per_page' => -1,'author' => $author_id) );
$all_author_categories = array();
foreach ($posts as $p) {
$author_categories_for_p = wp_get_object_terms( $p->ID,'product_cat');
if ( ! empty( $author_categories_for_p ) && ! is_wp_error( $author_categories_for_p ) ){
foreach ($author_categories_for_p as $author_category) {
$all_author_categories[$author_category->name] = $author_category;
}
}
}
// Then just loop over the collected categories and display them.
echo '<div class="d-flex flex-wrap">';
foreach($all_author_categories as $author_category) {
$author_category_link = get_term_link( $author_category );
$author_category_name = $author_categories[] = $author_category->name;
echo '<a href="'.esc_url( $author_category_link ).'" class="p-2 p-lg-5 bg-light text-center">';
echo $author_category_name;
echo '</a>';
}
echo '</div>';
备注:
- 当您发布大量文章时,此代码无法很好地扩展。您应该改用自定义查询。
- 我很确定最后不需要使用
wp_reset_postdata();
,因为您不会更改全局$post
对象。