1 回答

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
以下內(nèi)容將完成這項(xiàng)工作,將購物車中的免費(fèi)產(chǎn)品價(jià)格設(shè)置為零:
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 = 200;
$free_product_id = 4576;
// 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)
$cart_item['data']->set_price(0);
}
// Get cart subtotal incl. tax and discounts (excluding free product)
else {
$cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
}
}
// 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 );
// display notice after removal
wc_add_notice( __("Thank you! Here's your free product."), 'notice' );
}
// if below the minimum, remove the free product
elseif ( $cart_subtotal < $minimum_amount && isset( $free_item_key ) ) {
$cart->remove_cart_item( $free_item_key );
// display notice after removal
wc_add_notice( sprintf(
__("Your cart subtotal is less than %s and therefore, the free product was removed."), wc_price($cart_subtotal)
), 'notice' );
}
}
代碼位于活動(dòng)子主題(或活動(dòng)主題)的functions.php 文件中。經(jīng)過測(cè)試并有效。
- 1 回答
- 0 關(guān)注
- 118 瀏覽
添加回答
舉報(bào)