-1

How to disable BACS payment method for local delivery shipping method?

I have included the code below to my functions.php file, but it doesn't work.
Maybe someone could help me with this.

function my_custom_available_payment_gateways( $gateways ) {
    $chosen_shipping_rates = WC()->session->get( 'chosen_shipping_methods' );
    // When 'local delivery' has been chosen as shipping rate
    if ( in_array( 'local_delivery', $chosen_shipping_rates ) ) :
        // Remove bank transfer payment gateway
        unset( $gateways['bacs'] );
    endif;
    return $gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'my_custom_available_payment_gateways' );
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
George Pennet
  • 159
  • 3
  • 9

1 Answers1

2

You are not far. To make your code working you need to manipulate the data in the array of chosen shipping methods to get only the slugs in a foreach loop.

Here is the code:

add_filter( 'woocommerce_available_payment_gateways', 'unset_bacs_for_local_delivery' );

function unset_bacs_for_local_delivery( $gateways ) {
    // Not in backend (admin)
    if( is_admin() ) 
        return $gateways;

    // Initialising variables
    $chosen_shipping_method_ids = array();
    $chosen_shipping_methods = (array) WC()->session->get( 'chosen_shipping_methods' );

    // Iterating and manipulating the "chosen shipping methods" to get the SLUG
    foreach( $chosen_hipping_methods as $shipping_method_rate_id ) :
         $shipping_method_array = explode(':', $shipping_method_rate_id);
         $chosen_shipping_method_ids[] = $shipping_method_array[0];
    endforeach;

    //When 'local delivery' has been chosen as shipping method
    if ( in_array( 'local_delivery', $chosen_shipping_method_ids ) ) :
        // Remove bank transfer payment gateway
        unset( $gateways['bacs'] );
    endif;

    return $gateways;
}

This code is tested and is fully functional.

Code goes in functions.php file of your active child theme (or theme). Or also in any plugin php files.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399