Hide payment methods based on selected shipping method in WooCommerce [duplicate]

怎甘沉沦 提交于 2020-08-20 07:06:48

问题


I was trying to hide two payment method if one shipping method selected by adding code below to theme function.php

// Filter payment gatways for different shipping methods
function my_custom_available_payment_gateways( $gateways ) {
    $chosen_shipping_rates = WC()->session->get( 'chosen_shipping_methods' );
    if ( in_array( 'flat_rate:7', $chosen_shipping_rates ) ) {
        unset( $gateways['stripe'] );
        unset( $gateways['ppec_paypal'] );
    }
    endif;
    return $gateways;
}
 add_filter( 'woocommerce_available_payment_gateways', 
'my_custom_available_payment_gateways' );

everything is working. except I got this error on product page.

Warning:
in_array() expects parameter 2 to be array, null given in [theme function.php and line number]


回答1:


Use the following to prevent this error (also removed endif;):

// Filter payment gatways for different shipping methods
add_filter( 'woocommerce_available_payment_gateways', 'my_custom_available_payment_gateways', 10, 1 );
function my_custom_available_payment_gateways( $available_gateways ) {
if( is_admin() ) return $available_gateways; // Only for frontend

    $chosen_shipping_rates = (array) WC()->session->get( 'chosen_shipping_methods' );

    if ( in_array( 'flat_rate:12', $chosen_shipping_rates ) ) {
        unset( $available_gateways['stripe'], $available_gateways['ppec_paypal'] );
    }

    return $available_gateways;
}

Code goes in functions.php file of your active child theme (or active theme). It should works.



来源:https://stackoverflow.com/questions/55477809/hide-payment-methods-based-on-selected-shipping-method-in-woocommerce

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