Show WooCommerce product tag name set for a product with a shortcode
If you have only one product tag set for each product, the following shortcode function will output the product tag term name set for the current product (or a string of coma separated term names, when there are multiple terms set for a product). It works also for a defined product Id as argument in the shortcode (see usage examples).
The function code:
add_shortcode( 'wc_product_tag', 'get_tag_term_name_for_product_id' );function get_tag_term_name_for_product_id( $atts ) { // Shortcode attribute (or argument) extract( shortcode_atts( array( 'taxonomy' => 'product_tag', // The WooCommerce "product tag" taxonomy (as default) 'product_id' => get_the_id(), // The current product Id (as default) ), $atts, 'wc_product_tag' ) ); $term_names = (array) wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') ); if( ! empty($term_names) ){ // return a term name or multiple term names (in a coma separated string) return implode(', ', $term_names); }}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
USAGE examples:
- For the current product:
[wc_product_tag]
or in php:echo do_shortcode('[wc_product_tag]');
- For a defined product id:
[wc_product_tag product_id="37"]
or in php:echo do_shortcode('[wc_product_tag product_id="37"]');
This also works for any product custom taxonomy, as WooCommerce product category…
To display WooCommerce product category term names set for a product you need to replace:
'taxonomy' => 'product_tag', // The WooCommerce "Product Tag" taxonomy (as default)
by the following line:
'taxonomy' => 'product_cat', // The WooCommerce "Product Category" taxonomy (as default)