WordPress:从作者那里获取条款

WordPress: Get terms from author

在作者存档页面上,我想显示作者有 posts(在我的例子中是 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();

问题是产品类别出现了多次。我猜该产品类别中的每个 post。

有什么方法可以先收集条款并仅在产品类别中按 post 的计数排序后显示它们?

您应该首先将所有类别收集到一个容器数组中。通过在向数组添加类别时使用类别的 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>';

备注:

  1. 当您有很多帖子时,此代码无法很好地扩展。您应该改用自定义查询。
  2. 我很确定最后不需要 wp_reset_postdata();,因为您没有改变全局 $post 对象。