我在Woocommerce商店中开设了各种产品类别。
我想对所有属于杜鹃产品类别的产品都享受20%的折扣
目前,我要实现的所有目标是在我的functions.php中设置销售价格
它尝试如下:
/*
* For a specific date, 20% off all products with product category as cuckoo clock.
*/
function cuckoo_minus_twenty($sale_price, $product) {
$sale_price = $product->get_price() * 0.8;
return $sale_price;
};
// add the action
add_filter( 'woocommerce_get_sale_price', 'cuckoo_minus_twenty', 10, 2 );
如果我在计算后将var_dump的结果转储为$ sale_price的结果,则会得到正确的答案,但是前端的价格显示会剔除正常价格并将销售价格显示为正常价格。
是否可以使用挂钩/过滤器来实现此目的?
我还尝试通过以下方式设置销售价格:
$product->set_sale_price($sale_price);
无济于事。
woocommerce_get_sale_price
自WooCommerce 3起,该钩子已被弃用,并由代替woocommerce_product_get_sale_price
。
产品显示的价格也会被缓存。当销售价格处于活动状态时,常规价格也处于活动状态。
尝试以下方法:
// 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 )
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($sale_price) || $sale_price == 0 )
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;
$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文件中。
经过测试,可以在单个产品,商店,产品类别和标签归档页面上使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句