1 回答

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"]
- 1 回答
- 0 關注
- 213 瀏覽
添加回答
舉報