亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過短代碼獲取 Woocommerce 產品標簽帖子計數

通過短代碼獲取 Woocommerce 產品標簽帖子計數

PHP
倚天杖 2023-08-11 18:03:28
我需要計算整個網站上使用“產品標簽”的次數。每個產品都有許多與之相關的標簽。我考慮過創建一個短代碼,然后在需要時可以引用。我在下面創建的短代碼會使網站崩潰。// function function tag_count_shortcode() {  // Identify the tag ID and then run a count. $term = get_tag( $tag_ID );$count = $term->count;  // Output the total number of times a tag is usedreturn $count;} // register shortcodeadd_shortcode('tagcount', 'tag_count_shortcode'); 我不確定我哪里出了問題。非常感謝任何幫助。平臺:WordPress | 包含代碼的文件:“Functions.php”
查看完整描述

1 回答

?
largeQ

TA貢獻2039條經驗 獲得超8個贊

這是關于產品標簽,它是 WooCommerce 自定義分類法,而不是 WordPress 標簽。

此外,一個產品可以有多個產品標簽,因此以下代碼將處理第一個產品標簽術語的計數。這個短代碼還處理一些參數:

  • (也taxonomy可以處理任何自定義分類法、WordPress 標簽和類別)- 默認情況下:產品標簽

  • term_id可以處理任何定義的術語 ID) - 默認情況下它會在單個產品頁面上獲取術語

  • -post_id默認情況下當前產品 ID

代碼:

function term_count_shortcode( $atts ) {

    extract( shortcode_atts( array(

        'taxonomy'  => 'product_tag', // Product tag taxonomy (by default)

        'term_id' => 0,

        'post_id' => get_queried_object_id(), // The current post ID

    ), $atts ) );


    // For a defined term ID

    if( $term_id > 0 ) {

        // Get the WP_term object

        $term = get_term_by( 'id', $term_id, $taxonomy );


        if( is_a( $term, 'WP_Term' ) )

            $count = $term->count;

        else

            $count = 0;

    }

    // On product single pages

    elseif ( is_product() && $term_id == 0 && $post_id > 0 ) {

        // Get the product tag post terms

        $terms = get_the_terms( $post_id, $taxonomy );

        // Get the first term in the array

        $term  = is_array($terms) ? reset( $terms ) : '';


        if( is_a( $term, 'WP_Term' ) )

            $count = $term->count;

        else

            $count = 0;

    } else {

        $count = false;

    }

    return $count;

}

add_shortcode('term_count', 'term_count_shortcode');

代碼位于活動子主題(或活動主題)的 function.php 文件中。經過測試并有效。


用法:

1)。基本用法:顯示產品單頁第一個產品標簽計數:[term_count]

2)。與參數一起使用:

  • 使用定義的術語 ID:[term_count term_id="58"]

  • 具有定義的術語 ID 和分類法:[term_count term_id="15" taxonomy="product_cat"]

  • 使用定義的術語 ID 和帖子 ID:[term_count term_id="15" post_id="37"]


查看完整回答
反對 回復 2023-08-11
  • 1 回答
  • 0 關注
  • 213 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號