【问题标题】:Get the Product tags for the current product only in WooCommerce仅在 WooCommerce 中获取当前产品的产品标签
【发布时间】:2018-07-18 00:55:44
【问题描述】:

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

我发现了有关最流行标签的问题,但不是针对那个。

【问题讨论】:

    标签: php wordpress woocommerce product custom-taxonomy


    【解决方案1】:

    您可以通过这种方式将函数 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()

    【讨论】:

    • 非常感谢,成功了!但是我怎么能显示带有链接的标签呢?现在我只显示标签的标题。
    • 很抱歉,感谢您提醒我。感谢您的代码,这正是我多年来一直在寻找的。​​span>
    【解决方案2】:

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

    示例

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      相关资源
      最近更新 更多