Show hide payment methods based on selected shipping method in Woocommerce

烂漫一生 提交于 2019-12-02 04:34:05

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!