【问题标题】:Add specific info on single product page based on "Tag ID" in WooCommerce在 WooCommerce 中基于“标签 ID”在单个产品页面上添加特定信息
【发布时间】:2021-02-17 00:26:05
【问题描述】:

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

我想查看一个简单产品中的所有标签,如果遇到要打印的 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>'; 
        }
    }
}

有人可以指导我如何做到这一点吗?

【问题讨论】:

    标签: php wordpress woocommerce tags product


    【解决方案1】:

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

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

    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 );
    

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2022-07-26
      • 2017-09-13
      • 1970-01-01
      • 2018-04-30
      • 2021-07-13
      • 2022-01-12
      • 2018-07-07
      • 2018-04-23
      相关资源
      最近更新 更多