问题描述
我已根据每个购物车的数量添加了渐进式定价。我正在努力的是从产品中反映出$default_price
(而不是现在手动添加的价格),并以此设置新价格的布局(default_price具有删除线):
add_action( 'woocommerce_before_calculate_totals','add_custom_price',20,1);
function add_custom_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
foreach ( $cart->get_cart() as $item ) {
$quantity = $item['quantity'];
$discount_price = 0.008333333333;
$default_price = 4.25;
$minimum = 10;
$maximum = 100;
if( $quantity > $minimum ) {
if( $quantity > $maximum ) {
$new_price = $default_price - ($discount_price * ($maximum - $minimum));
}
else {
$new_price = $default_price - ($discount_price * ($quantity - $minimum));
}
$item['data']->set_price( '<del>' . $default_price . '</del> <strong>' . $new_price . '</strong>');
}
}
}
编码的$item['data']->set_price( '<del>' . $default_price . '</del> <strong>' . $new_price . '</strong>');
是错误的,但是如何反映这一点,以便它可以接受html元素?
解决方法
对于您想要获得的东西,可以使用以下内容:
-
使用
woocommerce_before_calculate_totals
动作挂钩来计算总数 -
woocommerce_cart_item_price
过滤器挂钩可确保删除原始价格。 -
通过在代码中添加注释标签的解释
function action_woocommerce_before_calculate_totals( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Settings
$discount_price = 0.008333333333;
$minimum = 10;
$maximum = 100;
// Iterating though each cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Product quantity in cart
$quantity = $cart_item['quantity'];
// Quantity greater than minimum
if ( $quantity > $minimum ) {
// Default price
$default_price = $cart_item['data']->get_price();
// Quantity greater than maximum
if ( $quantity > $maximum ) {
$new_price = $default_price - ( $discount_price * ( $maximum - $minimum ) );
} else {
$new_price = $default_price - ( $discount_price * ( $quantity - $minimum ) );
}
// Set price
$cart_item['data']->set_price( $new_price );
}
}
}
add_action( 'woocommerce_before_calculate_totals','action_woocommerce_before_calculate_totals',10,1 );
function filter_woocommerce_cart_item_price( $price_html,$cart_item,$cart_item_key ) {
// Get the product object
$product = $cart_item['data'];
// Is a WC product
if ( is_a( $product,'WC_Product' ) ) {
// Get reqular price
$regular_price = $product->get_regular_price();
// New price
$new_price = $cart_item['data']->get_price();
// NOT empty and NOT equal
if ( ! empty ( $regular_price ) && $regular_price != $new_price ) {
// Output
$price_html = '<del>' . wc_price( $regular_price ) . '</del> <ins>' . wc_price( $new_price ) . '</ins>';
}
}
return $price_html;
}
add_filter( 'woocommerce_cart_item_price','filter_woocommerce_cart_item_price',3 );