下面是对我之前的一个问题的Alter Woocommerce product name when price is on sale个回答代码,即根据销售价格附加产品名称.

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

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函数,我不确定它是否适合这个场景.我try 使用了标签名称的几个版本(Hard-Goods、Hard_Goods等),但都无济于事.

推荐答案

使用has_term() wordpress条件函数定位产品标签(S)如下:

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,而不是名称.

Php相关问答推荐

419注册期间Laravel 11中的错误

我的docker—compose lamp stack在软件更新后不工作:Containerconfig错误'''

邮箱打开跟踪器不工作时发送邮件使用laravel调度程序

WooCommerce中仅在单一产品和产品档案页面中将小数设置为大写

PHP,ZipArchive删除一个空文件?

通过注册在Laravel中分配角色

我的邮箱中的链接在我的URL中添加了一个

创建一个Woocommerce我的帐户订单页面,仅显示已完成的订单

在WooCommerce中只允许高价产品的BACS付款

即使在WooCommerce购物车中添加了两次产品,也要将所有项目设置为空白行

可以';exec、system和shell_exec PHP函数中的命令字符串上的字符数不得超过8175

invalid_grant 和无效的 JWT 签名

循环中未序列化数组显示的问题

Windows 身份验证在 IIS 中验证什么?我可以在我的情况下禁用匿名身份验证吗?

来自 GoDaddy 的邮箱在 Gmail 中显示为via

正则表达式请帮我从内容中找到这个词

显示时间范围内的可用空位,同时考虑已预订的空位

使用 RSA 2048 公钥验证 RSA PKCS#1v1.5 SHA 256 签名

遇到特定键时修改二维数组以创建嵌套数据集

如何在 Laravel 中验证多个输入?