通过短代码获取 Woocommerce 产品标签帖子计数

我需要计算整个网站上使用“产品标签”的次数。每个产品都有许多与之相关的标签。


我考虑过创建一个短代码,然后在需要时可以引用。我在下面创建的短代码会使网站崩溃。


// 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 used

return $count;

// register shortcode

add_shortcode('tagcount', 'tag_count_shortcode'); 

我不确定我哪里出了问题。非常感谢任何帮助。


平台:WordPress | 包含代码的文件:“Functions.php”


倚天杖
浏览 166回答 1
1回答

largeQ

这是关于产品标签,它是 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"]
打开App,查看更多内容
随时随地看视频慕课网APP