更改特定产品标签的 Woocommerce 产品名称

问题描述 投票:0回答:1

按照在促销时更改 Woocommerce 产品名称回答我之前的问题之一的代码,根据促销价格附加产品名称。

现在,我正在尝试为具有特定产品标签的产品添加相同的功能:

add_filter( 'the_title', 'change_product_title', 10, 2 );
function change_product_title( $post_title, $post_id ) {
    if( get_post_type($post_id) === 'product' ) {
        $product = wc_get_product($post_id);

        if( is_a($product, 'WC_Product') && $product->get_sale_price() > 0 ) {
            $post_title .= ' NET';
        }else if( is_a($product, 'WC_Product') && has_tag( $tag = 'Hard Goods', $post = null ) ){
            $post_title .= 'NET';
        }
    }
    return $post_title;
}

add_filter( 'woocommerce_product_variation_get_name', 'change_product_name', 10, 2 );
add_filter( 'woocommerce_product_get_name', 'change_product_name', 10, 2 );
function change_product_name( $name, $product ) {
    if ( $product->get_sale_price() > 0 ){
        $name .= ' NET';
    }else if( has_tag( $tag = 'Hard Goods', $post = null )){
        $name .= ' NET';
    }
    return $name;
}

这段代码没有产生预期的效果。我从未使用过 has_tag 函数,我不确定它是否适合这种情况。我尝试过使用多个版本的标签名称(hard-goods、Hard_Goods 等),但均无济于事。

php wordpress woocommerce product taxonomy-terms
1个回答
0
投票

使用

has_term()
WordPress 条件函数来定位产品标签,如下所示:

add_filter( 'the_title', 'change_product_title', 10, 2 );
function change_product_title( $post_title, $post_id ) {
    if( get_post_type($post_id) === 'product' ) {
        $product = wc_get_product($post_id);

        if( ( is_a($product, 'WC_Product') && $product->get_sale_price() > 0 ) 
        || has_term( 'Hard Goods', 'product_tag', $post_id ) ) {
            $post_title .= ' NET';
        }
    }
    return $post_title;
}

add_filter( 'woocommerce_product_variation_get_name', 'change_product_name', 10, 2 );
add_filter( 'woocommerce_product_get_name', 'change_product_name', 10, 2 );
function change_product_name( $name, $product ) {
    if ( $product->get_sale_price() > 0 || has_term( 'Hard Goods', 'product_tag', $product->get_id() ) ) {
        $name .= ' NET';
    }
    return $name;
}

应该可以。

您最好使用产品标签 slugterm ID 而不是名称。

© www.soinside.com 2019 - 2024. All rights reserved.