I have an issue with Woocommerce. I would like to hide certain shipping methods based on the choice of payment method.
I want all 3 payment methods ("bacs", "cod" and "przelewy24") to be always visible. Based on the choice of the payment method, there should be only 2 shipping methods shown:
If payment method = "bacs" or "przelewy24", then I want only those 2 shipping methods to be shown:
flexible_shipping_single:25 flexible_shipping_single:26
If payment method = "cod", then I want only those 2 shipping methods to be shown:
flexible_shipping_single:23 flexible_shipping_single:24
I know that I can easily hide payment methods based on the shipping method, but I need it to be the other way around.
Do you guys know how can it be solved? :)
I was trying to figure it out using this thread: Disable shipping method based on chosen payment method in Woocommerce
But I failed :(
add_action( 'woocommerce_package_rates','show_hide_shipping_methods', 10, 2 );
function show_hide_shipping_methods( $rates, $package ) {
// HERE Define your targeted shipping method ID
$chosen_payment_method = WC()->session->get('chosen_payment_method');
if( $payment_method == 'cod' ){ //if cod, hide unnecessary shipping methods
unset($rates['flexible_shipping_single:25']);
unset($rates['flexible_shipping_single:26']);
}
elseif ( $payment_method == 'przelewy24' ) //if przelewy24, hide unnecessary shipping methods
{
unset($rates['flexible_shipping_single:23']);
unset($rates['flexible_shipping_single:24']);
}
elseif ( $payment_method == 'bacs' ) //if bacs, hide unnecessary shipping methods
{
unset($rates['flexible_shipping_single:23']);
unset($rates['flexible_shipping_single:24']);
}
return $rates;
}
add_action( 'woocommerce_review_order_before_payment', 'payment_methods_trigger_update_checkout' );
function payment_methods_trigger_update_checkout(){
// jQuery code
?>
<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
}
// TO BE COMPLETLY HONEST, I DON'T REALLY KNOW WHAT I WAS SUPPOSED TO DO BELOW
add_action( 'woocommerce_checkout_update_order_review', 'refresh_shipping_methods' );
function refresh_shipping_methods( $post_data ){
// HERE Define your targeted shipping method ID
$bool = true;
if ( WC()->session->get('chosen_payment_method') === 'cod' )
$bool = false;
if ( WC()->session->get('chosen_payment_method') === 'przelewy24' )
$bool = false;
if ( WC()->session->get('chosen_payment_method') === 'bacs' )
$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();
}