Show hide payment methods based on selected shippi

2020-04-20 21:00发布

I would like to hide some payment method and enable another one when I select a specified “Shipping Method" in flexible Shipping plugin form wpdesk.

I have already tried that code:

add_filter( 'woocommerce_available_payment_gateways', 'gateway_disable_shipping_326' );
function gateway_disable_shipping_326( $available_gateways ) {
    global $woocommerce;

    if ( !is_admin() ) {
        $chosen_methods  = WC()->session->get( 'chosen_shipping_methods' );
        $chosen_shipping = $chosen_methods[0];

        if ( isset( $available_gateways['payment_method_cod'] ) && 0 === strpos( $chosen_shipping, 'flat_rate:6' ) ) {
            unset( $available_gateways['payment_method_cod'] );
        }
    }
    return $available_gateways; 
}

and this one

function my_custom_available_payment_gateways( $gateways ) {
    $chosen_shipping_rates = WC()->session->get( 'chosen_shipping_methods' );
    if ( in_array( 'flat_rate:6', $chosen_shipping_rates ) ) :
        unset( $gateways['payment_method_cod'] );
        endif;
    if ( in_array( 'flat_rate:8', $chosen_shipping_rates ) ) :
        unset( $gateways['payment_method_przelewy24'] );
    endif;
    return $gateways;
}

add_filter( 'woocommerce_available_payment_gateways', 'my_custom_available_payment_gateways' );

The link to my website: [www.dajati.pl][1]

1条回答
The star\"
2楼-- · 2020-04-20 21:40

The following code example will enable / disable payment gateways based on chosen shipping method.

In this example, we have 3 shipping methods and 3 payment gateways. Each selected shipping method will enable only one different payment gateway.

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateways_based_on_chosen_shipping_method' );
function payment_gateways_based_on_chosen_shipping_method( $gateways ) {
    // Get chosen shipping methods
    $chosen_shipping_methods = (array) WC()->session->get( 'chosen_shipping_methods' );

    if ( in_array( 'flat_rate:12', $chosen_shipping_methods ) )
    {
        unset( $gateways['bacs'] );
        unset( $gateways['cod'] );
    }
    elseif ( in_array( 'flat_rate:14', $chosen_shipping_methods ) )
    {
        unset( $gateways['bacs'] );
        unset( $gateways['paypal'] );
    }
    elseif ( in_array( 'free_shipping:10', $chosen_shipping_methods ) )
    {
        unset( $gateways['cod'] );
        unset( $gateways['paypal'] );
    }

    return $gateways;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

To be able to get the correct shipping method ID you can use your browser inspector, this way:

enter image description here

查看更多
登录 后发表回答