افزودن اتوماتیک هدیه به سبد خرید
- ۲۴ دی ۱۴۰۲
- بدون نظر
- فانکشن های ووکامرس
- گزارش خطا
فانکشن 8:
اگر میخواید هنگام خرید به سبدهای خرید بالاتر از X تومان، یک محصول به عنوان هدیه اضافه بشه، از کد زیر استفاده کنید.
نحوه استفاده: قرار دادن کد در انتهای فایل فانکشن قالب فعال تون
راهنمایی: در خط 8 و 45، آی دی محصولی که به عنوان هدیه قراره به سبد اضافه بشه رو قرار بدید.
و همچنین در خط 9، مینیمم مقدار سبد خرید که شامل هدیه میشه رو درج کنید. (به تومان)
// Add free gifted product for specific cart subtotal
add_action( 'woocommerce_before_calculate_totals', 'check_free_gifted_product_1000000' );
function check_free_gifted_product_1000000( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Settings
$free_product_id = 123; // GIFT PRODUCT ID
$targeted_subtotal = 100000; // MINIMUM AMOUNT OF CART
$cart_subtotal = 0; // Initializing
// Loop through cart items (first loop)
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// When free product is in cart
if ( $free_product_id == $cart_item['variation_id'] ) {
$free_key = $cart_item_key;
$free_qty = $cart_item['quantity'];
$cart_item['data']->set_price(0); // Optionally set the price to zero
} elseif(38736 != $cart_item['product_id']) {
$cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
}
}
// If subtotal match and free product is not already in cart, add it
if ( ! isset($free_key) && $cart_subtotal >= $targeted_subtotal ) {
$cart->add_to_cart( $free_product_id );
}
// If subtotal doesn't match and free product is already in cart, remove it
elseif ( isset($free_key) && $cart_subtotal < $targeted_subtotal ) { $cart->remove_cart_item( $free_key );
}
// Keep free product quantity to 1.
elseif ( isset($free_qty) && $free_qty > 1 ) {
$cart->set_quantity( $free_key, 1 );
}
}
// Display free gifted product price to zero on minicart
add_filter( 'woocommerce_cart_item_price', 'change_minicart_free_gifted_item_price_1000000', 10, 3 );
function change_minicart_free_gifted_item_price_1000000( $price_html, $cart_item, $cart_item_key ) {
$free_product_id = 123; // GIFT PRODUCT ID
if( $cart_item['variation_id'] == $free_product_id ) {
return wc_price( 0 );
}
return $price_html;
}
اشتراک گذاری فانکشن: