I need to count the number of times a “product tag” is used across the website. Each product has a number of tags associated with it.
I thought about creating a shortcode which I can then reference when needed. The shortcode I have created below crashes the website.
// 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');
Im not sure where I am going wrong with this. Would really appreciate any assistance.
Platform: WordPress | File with code: “Functions.php”
Cheers
Advertisement
Answer
This is about product tags which is a WooCommerce custom taxonomy and not WordPress Tags.
Also a product can have many product tags, so the following code will handle the count on the first product tag term. This shortcode also handle some arguments:
- the
taxonomy
(can handle any custom taxonomy, WordPress tag and category too) – By default: product tag - the
term_id
(can handle any defined term ID) – by default it gets the term on single product pages - the
post_id
– By default the current product ID
The code:
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');
Code goes in function.php file of your active child theme (or active theme). Tested and works.
USAGE:
1). Basic usage: Display the first product tag count from product single page: [term_count]
2). Usage with arguments:
With a defined term ID:
[term_count term_id="58"]
With a defined term ID and Taxonomy:
[term_count term_id="15" taxonomy="product_cat"]
With a defined term ID and post ID:
[term_count term_id="15" post_id="37"]