[英]How to use cart total to change cart items prices in WooCommerce
I am trying to pass the total amount of the cart ( $GetTotalPrice
) from function cart_prices_GetPrice()
to function cart_prices_ApplyPrice()
, using a woocommerce_after_calculate_totals
and woocommerce_before_calculate_totals
hooks, but I get an empty value.
//Trying to get cart amount
add_action('woocommerce_after_calculate_totals', 'cart_prices_GetPrice');
function cart_prices_GetPrice() {
//Getting the cart amount
$GetTotalPrice = WC()->cart->get_cart_total();
return $GetTotalPrice;
}
//Applying custom price
add_action('woocommerce_before_calculate_totals', 'cart_prices_ApplyPrice');
function cart_prices_ApplyPrice( $cart_object ) {
//Getting the cart amount from first function
$totalprice = cart_prices_GetPrice(); // doesn't work and returns 0 :(
//price change to cost2
if( $totalprice != 0 && $totalprice >= 2000 ) {
foreach ( $cart_object->get_cart() as $cart_id => $cart_item ) {
// get products id
$product_id = $cart_item['product_id'];
if( $cart_item['product_id'] == $product_id ) {
// price change to cost2
$new_price1 = 0.20;
$cart_item['data']->set_price( $new_price1 );
}
}
}
}
同時,每個功能都可以完美運行。
我究竟做錯了什么? 是否有可能以某種方式鏈接兩個鈎子數據,以便第一個不返回空值?
更新:
我將無法拒絕鈎子woocommerce_before_calculate_totals
,因為我需要為購物車中的每個產品單獨降價。
當您出於多種原因想要更改購物車商品價格時,您根本不能在woocommerce_before_calculate_totals
中使用購物車總數……
相反,您將在woocommerce_before_calculate_totals
掛鈎中獲得購物車項目小計。 在下面的代碼中,我使用了包含稅費的折扣購物車商品小計:
add_action('woocommerce_before_calculate_totals', 'customize_cart_item_prices');
function customize_cart_item_prices( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Avoiding the hook repetition for price calculations
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$threshold_amount = 1000; // Min subtotal
$discount_rate = 0.2; // price discount rate (20%)
$cart_items = $cart->get_cart();
// Getting non discounted cart items subtotal
$subtotal_excl_tax = array_sum( wp_list_pluck( $cart_items, 'line_subtotal' ) );
$subtotal_tax = array_sum( wp_list_pluck( $cart_items, 'line_subtotal_tax' ) );
// Getting discounted cart items subtotal
$total_excl_tax = array_sum( wp_list_pluck( $cart_items, 'line_total' ) );
$total_tax = array_sum( wp_list_pluck( $cart_items, 'line_tax' ) );
if( ( $total_excl_tax + $total_tax ) >= $threshold_amount ) {
// Loop through cart items
foreach ( $cart_items as $item ) {
$price = $item['data']->get_price(); // Get price
$item['data']->set_price( $price * ( 1 - $discount_rate ) ); // Set new price
}
}
}
代碼進入活動子主題(或活動主題)的functions.php文件。 測試和工作。
請參閱Woocommerce 3 答案代碼中的更改購物車項目價格,以了解如何處理迷你車顯示的自定義購物車項目價格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.