Free shipping and gift message Woocommerce

and programmatically add gift to cart

          
//free shipping and present notification add_action( 'woocommerce_before_checkout_form', function() { echo custom_checkout_page_notice(); }); add_action( 'woocommerce_before_cart', function() { echo custom_checkout_page_notice(); }); add_shortcode('free_shipping_message', function() { if ( ! WC()->cart ) return ''; return custom_checkout_page_notice(); }); function custom_checkout_page_notice() { $free_shipping_threshold = 50; $gift_threshold = 60; $cart = WC()->cart; if ( ! $cart ) return; // Final subtotal after coupons, without shipping or fees $current_cart_total = $cart->get_cart_contents_total(); if ( $current_cart_total <= 0 ) { $message = 'Δωρεάν μεταφορικά με αγορές άνω των ' . strip_tags( wc_price( $free_shipping_threshold ) ) . '!'; } elseif ( $current_cart_total > 0 && $current_cart_total < $free_shipping_threshold ) { $remaining_amount = $free_shipping_threshold - $current_cart_total; $message = 'Ακόμη ' . strip_tags( wc_price( $remaining_amount ) ) . ' για δωρεάν μεταφορικά! <a href="' . esc_url( wc_get_page_permalink( 'shop' ) ) . '">Ψώνισε</a>'; } elseif ( $current_cart_total >= $free_shipping_threshold && $current_cart_total < $gift_threshold ) { $remaining_amount = $gift_threshold - $current_cart_total; $message = 'Έχεις δωρεάν μεταφορικά! Ακόμη ' . strip_tags( wc_price( $remaining_amount ) ) . ' για Δώρο Έκπληξη! <a href="' . esc_url( wc_get_page_permalink( 'shop' ) ) . '">Ψώνισε</a>'; } else { $message = 'Έχεις δωρεάν μεταφορικά & Δώρο Έκπληξη!'; } return '<div class="woocommerce-message">' . wp_kses_post( $message ) . '</div>'; } function maybe_handle_gift_product() { $gift_product_id = 3444; $threshold = 60; $cart = WC()->cart; if ( is_admin() || ! $cart ) return; // Get the amount before shipping and fees, but after discounts (i.e. final subtotal after coupons) $cart_total = $cart->get_cart_contents_total(); $gift_in_cart = false; $gift_key = ''; foreach ( $cart->get_cart() as $key => $item ) { if ( $item['product_id'] == $gift_product_id ) { $gift_in_cart = true; $gift_key = $key; break; } } if ( $cart_total >= $threshold ) { if ( ! $gift_in_cart ) { $cart->add_to_cart( $gift_product_id, 1, 0, [], [ 'is_auto_gift' => true ] ); } } else { if ( $gift_in_cart ) { $cart->remove_cart_item( $gift_key ); } } } add_action( 'woocommerce_cart_updated', 'maybe_handle_gift_product' ); function prevent_manual_gift_product_addition( $passed, $product_id, $quantity, $variation_id = null, $variations = null, $cart_item_data = [] ) { if ( $product_id == 3444 && empty( $cart_item_data['is_auto_gift'] ) ) { wc_add_notice( 'Αυτό το προϊόν δεν μπορεί να προστεθεί στο καλάθι χειροκίνητα.', 'error' ); return false; } return $passed; } add_filter( 'woocommerce_add_to_cart_validation', 'prevent_manual_gift_product_addition', 10, 6 );
Was this helpful?
YesNo

Leave a Reply