I have two shipping methods withd ids ‘flat_rate:1’ and ‘free_shipping:2’ and two payment methods with ids ‘cod’ and ‘pumcp’.
Conditions:
- When cod is selected I want to hide free_shipping:2 and show flat_rate:1.
- When pumcp is selected I want to hide flat_rate:1 and show free_shipping:2
- Both the payment methods should be visible and should not hide based on shipping method selection.
I am using following code from other stack overflow question but it hides cod payment method and I am unable to select that.
Can someone please explain what is the actual issue?
add_action( 'woocommerce_package_rates','show_hide_shipping_methods', 10, 2 );
function show_hide_shipping_methods( $rates, $package ) {
$chosen_payment_method = WC()->session->get('chosen_payment_method');
if( $chosen_payment_method == 'cod' ){
unset($rates['free_shipping:2']);
}
else if ( $chosen_payment_method == 'pumcp' )
{
unset($rates['flat_rate:1']);
}
return $rates;
}
add_action( 'woocommerce_review_order_before_payment', 'payment_methods_trigger_update_checkout' );
function payment_methods_trigger_update_checkout(){
?>
<script type="text/javascript">
(function($){
$( 'form.checkout' ).on( 'change blur', 'input[name^="payment_method"]', function() {
setTimeout(function(){
$(document.body).trigger('update_checkout');
}, 250 );
});
})(jQuery);
</script>
<?php
}
add_action( 'woocommerce_checkout_update_order_review', 'refresh_shipping_methods' );
function refresh_shipping_methods( $post_data ){
$bool= true;
if ( WC()->session->get('chosen_payment_method') === 'cod' ) {
$bool = false;
}
if ( WC()->session->get('chosen_payment_method') === 'pumcp' ) {
$bool = false;
}
// Mandatory to make it work with shipping methods
foreach ( WC()->cart->get_shipping_packages() as $package_key => $package ){
WC()->session->set( 'shipping_for_package_' . $package_key, $bool );
}
WC()->cart->calculate_shipping();
}