特价时更改 Woocommerce 产品名称

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

我们使用“NET”来标识正在销售的产品。我编写了以下代码,以便在产品开售或停售时自动向产品添加或删除 NET。

function change_product_titles( $post, $title ) {
    
    if ( !empty( get_post_meta( $post->get_id, '_sale_price', true ))){
        return $title.' NET';
    }else{
        return $title;
    }
}
add_filter( 'woocommerce_product_title', 'change_product_titles', 10, 2 );

这看起来很简单,但我在任何地方都没有看到预期的效果。

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

您没有使用正确的钩子和正确的方法...尝试以下方法,这将在产品标题(和产品名称)无处不在添加后缀,当产品出售时,无需不断更新产品名称:

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';
        }
    }
    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';
    }
    return $name;
}

代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。

您需要从管理员的产品标题中删除“NET”。

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