Created
March 22, 2022 11:15
-
-
Save wpflames/c0b853ee111526a024342feb234e30de to your computer and use it in GitHub Desktop.
Add fee to checkout for COD shipping except specific shipping zone
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // ========================================================================= | |
| // WooCommerce add fee to checkout for a gateway ID | |
| // ========================================================================= | |
| function add_checkout_fee_for_gateway() { | |
| // Check if specific shipping zone in the cart | |
| $shipping_class_target = 32; // shipping class ID | |
| $in_cart = false; | |
| foreach ( WC()->cart->get_cart_contents() as $key => $values ) { | |
| if ( $values[ 'data' ]->get_shipping_class_id() == $shipping_class_target ) { | |
| $in_cart = true; | |
| break; | |
| } | |
| } | |
| // Set additional fees to COD only if there is no specific shipping zone in the cart | |
| $chosen_gateway = WC()->session->get( 'chosen_payment_method' ); | |
| if ( !$in_cart && $chosen_gateway == 'cod' ) { | |
| WC()->cart->add_fee( 'Utánvét díja', 400 ); | |
| } | |
| } | |
| add_action( 'woocommerce_cart_calculate_fees', 'add_checkout_fee_for_gateway' ); | |
| // Refresh checkout on payment methods change | |
| function refresh_checkout_on_payment_methods_change(){ | |
| wc_enqueue_js( " | |
| $( 'form.checkout' ).on( 'change', 'input[name^=\'payment_method\']', function() { | |
| $('body').trigger('update_checkout'); | |
| }); | |
| "); | |
| } | |
| add_action( 'woocommerce_after_checkout_form', 'refresh_checkout_on_payment_methods_change' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment