Reputation: 13
I currently have active code in WooCommerce and it works fine. The code allows me to apply an extra cost when the customer chooses the "COD' pyament method, + € 1.7
What I would like to understand is this:
Is it possible to disable the extra cost when the customer chooses to collect the goods from our warehouse?
Here is the code:
// Add a custom fee based o cart subtotal
add_action( 'woocommerce_cart_calculate_fees', 'custom_handling_fee', 10, 1 );
function custom_handling_fee ( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( 'cod' === WC()->session->get('chosen_payment_method') ) {
$fee = 1.7;
$cart->add_fee( 'Extra per pagamento alla consegna', $fee, true );
}
}
// jQuery - Update checkout on methode payment change
add_action( 'wp_footer', 'custom_checkout_jqscript' );
function custom_checkout_jqscript() {
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?>
<script type="text/javascript">
jQuery( function($){
$('form.checkout').on('change', 'input[name="payment_method"]', function(){
$(document.body).trigger('update_checkout');
});
});
</script>
<?php
endif;
}
Upvotes: 1
Views: 743
Reputation: 29650
While cod
is a payment method, local_pickup
is a shipping method.
WC()->session->get( 'chosen_payment_method' );
WC()->session->get( 'chosen_shipping_methods' );
So to come to an answer to your question, you will have to use a combination of the 2.
So you get:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Chosen payment method
$chosen_payment_method = WC()->session->get( 'chosen_payment_method' );
// Chosen shipping method
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping_method = substr( $chosen_shipping_methods[0], 0, strpos( $chosen_shipping_methods[0], ':' ) );
// Compare payment method & shipping method
if ( $chosen_payment_method == 'cod' && $chosen_shipping_method != 'local_pickup' ) {
// Fee
$fee = 1.7;
// Add fee
$cart->add_fee( __( 'Extra per pagamento alla consegna', 'woocommerce'), $fee, true );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
// jQuery - Update checkout on method payment change
function custom_checkout_jqscript() {
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?>
<script type="text/javascript">
jQuery( function($){
$( 'form.checkout' ).on( 'change', 'input[name="payment_method"]', function(){
$( document.body ).trigger( 'update_checkout' );
});
});
</script>
<?php
endif;
}
add_action( 'wp_footer', 'custom_checkout_jqscript' );
Upvotes: 1