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



我需要计算一个";产品标签";在整个网站上使用。每种产品都有许多与之相关的标签。

我想过创建一个快捷代码,然后在需要时可以参考。我在下面创建的短代码使网站崩溃。

// 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|带有代码的文件:";函数.php">

干杯

这是关于产品标签的,它是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"]

最新更新