簡體   English   中英

WordPress:從作者那里獲取條款

[英]WordPress: Get terms from author

在作者存檔頁面上,我想顯示作者發布帖子(在我的情況下為 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>';

評論:

  1. 當您有很多帖子時,此代碼不能很好地擴展。 您應該改用自定義查詢。
  2. 我很確定wp_reset_postdata(); 最后不需要,因為您沒有更改全局$post對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM