我想做的是对我的每个WooCommerce产品采取常规价格,并根据几个条件动态创建销售价格。这将包括以下内容:
1)在商店页面产品上显示动态创建的销售价格。
2)购物车中显示的销售价格(购物车中的项目价格和总价反映动态销售价格)
3)结帐页和总数反映动态销售价格。
我研究了几个解决方案,得出了以下解决方案:
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;
}
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.7;
if( empty($sale_price) || $sale_price == 0 )
return $product->get_regular_price() * $rate;
else
return $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;
}
add_action( 'woocommerce_before_calculate_totals',
'set_cart_item_sale_price', 10, 1 );
function set_cart_item_sale_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
foreach( $cart->get_cart() as $cart_item ) {
$price = $cart_item['data']->get_sale_price();
$cart_item['data']->set_price( $price );
}
}
add_filter( 'woocommerce_cart_item_price',
'bbloomer_change_cart_table_price_display', 30, 3 );
function bbloomer_change_cart_table_price_display( $price, $values,
$cart_item_key ) {
$slashed_price = $values['data']->get_price_html();
$is_on_sale = $values['data']->is_on_sale();
if ( $is_on_sale ) {
$price = $slashed_price;
}
return $price;
}
除购物车表汇总外,此项工作将显示原始价格汇总,而不是动态销售价格汇总。一定有一种更简单的方法。任何帮助都将不胜感激。谢谢,朱尔斯