在 WooCommerce 3 中以编程方式仅设置特定产品的销售价格 [英] Set only specific products sale price programmatically in WooCommerce 3
本文介绍了在 WooCommerce 3 中以编程方式仅设置特定产品的销售价格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想以编程方式设置产品销售价格在 WooCommerce 3 中,但仅适用于特定产品 ID.
I would like to Set product sale price programmatically in WooCommerce 3 but only for specific products Ids.
是否有可能以及如何使用 此线程 代码?
Is it possible and how can I target only specific products using this thread code?
我无法让它仅适用于特定产品.
I haven't be able to make it work for specific products only.
感谢任何帮助.
推荐答案
只设置特定的产品销售价格(产品ID在第一个函数中定义),试试这个:
To Set only specific product sale price (the products IDs are defined in the 1st function), try this:
// HERE below in the array set your specific product IDs
function specific_product_ids(){
return array(37, 43, 57); // <=== <=== <=== <=== Your Product IDs
}
// Generating dynamically the product "regular price"
add_filter( 'woocommerce_product_get_regular_price', 'custom_dynamic_regular_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_regular_price', 'custom_dynamic_regular_price', 10, 2 );
function custom_dynamic_regular_price( $regular_price, $product ) {
if( ( empty($regular_price) || $regular_price == 0 ) && in_array($product->get_id(), specific_product_ids() ) )
return $product->get_price();
else
return $regular_price;
}
// Generating dynamically the product "sale price"
add_filter( 'woocommerce_product_get_sale_price', 'custom_dynamic_sale_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_sale_price', 'custom_dynamic_sale_price', 10, 2 );
function custom_dynamic_sale_price( $sale_price, $product ) {
$rate = 0.8;
if( ( empty($regular_price) || $regular_price == 0 ) && in_array($product->get_id(), specific_product_ids() ) )
return $product->get_regular_price() * $rate;
else
return $sale_price;
};
// Displayed formatted regular price + sale price
add_filter( 'woocommerce_get_price_html', 'custom_dynamic_sale_price_html', 20, 2 );
function custom_dynamic_sale_price_html( $price_html, $product ) {
if( $product->is_type('variable') ) return $price_html;
if( in_array($product->get_id(), specific_product_ids() ) ) {
$price_html = wc_format_sale_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ), wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) ) ) . $product->get_price_suffix();
}
return $price_html;
}
代码位于您的活动子主题(活动主题)的 function.php 文件中.
Code goes in function.php file of your active child theme (active theme).
延续:
仅为特定设置在 woocommerce 购物车中生成销售价格的产品
这篇关于在 WooCommerce 3 中以编程方式仅设置特定产品的销售价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文