在 WooCommerce 中基于 "Tag ID" 在单个产品页面上添加特定信息

Add specific info on single product page based on "Tag ID" in WooCommerce

在 WooCommerce 单个产品页面的元部分中,我需要提取一个标签 ID (135)。

我想查看一个简单产品中的所有标签,如果我遇到要打印 ID 为 135 的标签:

我正在尝试一些操作,但无法获取该标签 ID

add_action('woocommerce_product_meta_end', 'wh_renderProductTagDetails');

function wh_renderProductTagDetails()
{
    global $product;
    $tags = get_the_terms($product->get_id(), 'product_tag');
    //print_r($tags);
    if (empty($tags))
        return;
    foreach ($tags as $tag_detail)
    {
        
        if ($tags (135)){
        
        // echo '<p> Material: Leather</p>'; 
       echo '<p> Material: ' . $tag_detail->name . '</p>'; 
        }
    }
}

有人可以指导我如何操作吗?

您的代码包含一些小错误。

这应该足够了 - 通过代码中添加的注释标签进行解释。

function action_woocommerce_product_meta_end() {
    global $product;
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Set taxonmy
        $taxonomy = 'product_tag';
        
        // Get the terms
        $terms = get_the_terms( $product->get_id(), $taxonomy );
        
        // Error or empty
        if ( is_wp_error( $terms ) ) {
            return $terms;
        }

        if ( empty( $terms ) ) {
            return false;
        }
        
        // Loop trough
        foreach ( $terms as $index => $term ) {
            // Product tag Id
            $term_id = $term->term_id;
            
            // DEBUG: remove afterwards
            echo '<p>DEBUG - Term id: ' . $term_id . '</p>';
            
            // Compare
            if ( $term_id == 135 ) {
                echo '<p>Material: ' . $term->name . '</p>'; 
            }
        }
    }
}
add_action( 'woocommerce_product_meta_end', 'action_woocommerce_product_meta_end', 10, 0 );