根据 WooCommerce 中选择的运输方式隐藏付款方式

Hide payment methods based on selected shipping method in WooCommerce

如果通过在主题下方添加代码选择了一种送货方式,我试图隐藏两种付款方式 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' );

一切正常。除了我在产品页面上收到此错误。

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

使用以下内容来防止此错误(也已删除 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;
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。它应该有效。