Show WooCommerce product tag name set for a product with a shortcode

1.7k views Asked by At

As the title says I’m looking for a shortcode I can use to show the tag of a specific product. All my products have only one product tag set for each.

For example, if the product with ID: 1250 has the tag “Horse” I need the way to put a shortcode specifying the ID of the product and show your respective tag. In the example the shortcode should show on the screen the word “Horse”

Tyring to modify the following code to achieve it:

$terms = wp_get_post_terms( get_the_id(), 'product_tag' );

if( count($terms) > 0 ){
foreach($terms as $term){
$term_id = $term->term_id; // Product tag Id
$term_name = $term->name; // Product tag Name
$term_slug = $term->slug; // Product tag slug
$term_link = get_term_link( $term, 'product_tag' );

$output[] = '.$term_name.';
}

$output = implode( ', ', $output );

echo $output;
}

But I don't have the enough knowledge to achieve it

Any help is appreciated.

1

There are 1 answers

3
LoicTheAztec On BEST ANSWER

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)