仅在WooCommerce中获取当前产品的产品标签

时间:2018-02-07 16:32:45

标签: php wordpress woocommerce product custom-taxonomy

如何仅显示当前单个产品页面的产品标签,而不显示所有产品标签?

我发现了大多数热门标签的问题但不是。

2 个答案:

答案 0 :(得分:5)

您可以将功能wp_get_post_terms()功能用于WooCommerce' product_tag'自定义分类和定义的产品ID

$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;
}

经过测试和工作。

您也可以用动态产品ID变量替换get_the_id()

答案 1 :(得分:0)

您现在可以使用wc_get_product_tag_list()函数来获取产品标签的列表。它支持在元素前后提供分隔符。

示例

<?php
    global $product;
?>
    <div class="product-tags">
        <?php echo wc_get_product_tag_list( $product->get_id(), ', ' ); ?>
    </div>
相关问题