Get the Product tags for the current product only in WooCommerce

故事扮演 提交于 2020-02-22 07:58:21

问题


How can I display only the product tags for the current single product page and not all the products tags?

I've found questions about most popular tags but not for that.


回答1:


You can use the function wp_get_post_terms() function for WooCommerce 'product_tag' custom taxonomy and a defined product id this way:

$output = array();

// get an array of the WP_Term objects for a defined product ID
$terms = wp_get_post_terms( get_the_id(), 'product_tag' );

// Loop through each product tag for the current product
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' ); // Product tag link

        // Set the product tag names in an array
        $output[] = '<a href="'.$term_link.'">'.$term_name.'</a>';
    }
    // Set the array in a coma separated string of product tags for example
    $output = implode( ', ', $output );

    // Display the coma separated string of the product tags
    echo $output;
}

Tested and works.

You can replace get_the_id() by a dynamic product Id variable too.



来源:https://stackoverflow.com/questions/48668811/get-the-product-tags-for-the-current-product-only-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!