我有一个代码,当总数为 49.99 时,我想自动将免费产品添加到购物车,并在总数较少时将其删除。
我有这个代码:
// add_action( 'woocommerce_before_calculate_totals', 'conditionally_add_free_product' );
function conditionally_add_free_product( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Settings
$minimum_amount = 49.99;
$free_product_id = 142984;
// Initializing
$cart_subtotal = 0;
$cart_items = $cart->get_cart();
// Loop through cart items (first loop)
foreach ( $cart_items as $cart_item_key => $cart_item ) {
// When free productis is cart
if ( $cart_item['data']->get_id() == $free_product_id ) {
$free_item_key = $cart_item_key; // Free product found (get its cart item key)
}
// Get cart subtotal incl. tax and discounts (excluding free product)
else {
$cart_subtotal += $cart_item['line_total'];
}
}
// When cart total is up to the minimum amount, add the free product if not already there
if ( $cart_subtotal >= $minimum_amount && ! isset( $free_item_key ) ) {
$cart_item_key = $cart->add_to_cart( $free_product_id );
}
// if below the minimum, remove the free product
elseif ( $cart_subtotal < $minimum_amount && isset( $free_item_key ) ) {
$cart->remove_cart_item( $free_item_key );
}
}
在普通购物车中一切正常,但迷你购物车小部件会引发错误“未定义索引:line_total”并且免费产品未添加到迷你购物车中。
当我点击购物车链接时,一切都会更新。
我使用店面,并且只启用了 WooCommerce。
也许有人可以指出问题出在哪里?
也许我用错了钩子?