根据 WooCommerce 中选定的运输方式隐藏付款方式 [英] Hide payment methods based on selected shipping method in WooCommerce

查看:27
本文介绍了根据 WooCommerce 中选定的运输方式隐藏付款方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果通过将下面的代码添加到主题 function.php 选择了一种运输方式,我试图隐藏两种付款方式

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.

警告:
in_array() 期望参数 2 为数组,[主题函数.php 和行号] 中给出的空值

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

推荐答案

使用以下内容来防止这个错误(也删除了endif;):

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;
}

代码位于活动子主题(或活动主题)的 functions.php 文件中.它应该有效.

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

这篇关于根据 WooCommerce 中选定的运输方式隐藏付款方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆