有条件地隐藏可用的付款网关



在WooCommerce中,我有一个特定产品,由于可以通过COD订购,但由于法律原因无法在线支付。

我已经写了一个自定义的挂钩功能,以隐藏付款表(Inspire Commerce Credit Card Payments)当该特定产品在购物车中。

当我回声$available_gateways时,我在数组中看到了两个选项," COD"one_answers" INSPIRE" - 但是当我用代码隐藏Inspire时,两个网关都会消失,我收到了此错误消息:

对不起,似乎没有可用的付款方式 状态。如果您需要协助或希望进行,请与我们联系 替代安排。

关于我为什么不能只有鳕鱼的任何想法?

这是我的功能代码:

function dfg_hide_payment_form($available_gateways) {
    if ($_customer['dfg-pay-later-enabled'] == 1) {
        if( is_checkout() ) {  
            global $woocommerce, $_customer;
            $packages = $_customer['dfg-package-ids'];
            foreach ($packages as $package) {
                if (gs_woo_in_cart($package)) {
                    unset($available_gateways['inspire']);
                }
            }
        }
    } else {
        unset($available_gateways['cod']);
    }
}
add_filter('woocommerce_available_payment_gateways', 'dfg_hide_payment_form', 1);

谢谢

主要问题,始终在使用过滤器钩时始终返回主函数参数$available_gateways)。

同样,当使用woocommerce_available_payment_gateways钩子时,不要忘记仅针对前端,以避免在WooCommerce设置中进行管理问题。

我在此答案中使用了一种交互方式,以检查您的特定产品是否在购物车中。如果产品在购物车中,我将" Inspire"支付网关(替换错误的变量名称)

这是此代码:

add_filter('woocommerce_available_payment_gateways', 'conditional_hiding_payment_gateway', 1, 1);
function conditional_hiding_payment_gateway($available_gateways) {
    // Not in backend (admin)
    if( is_admin() ) 
        return $available_gateways;
    global $_customer;
    if ($_customer['dfg-pay-later-enabled'] == 1) {
        // HERE set your specific product ID
        $specific_product = 295;
        $is_in_cart = false;
        // Iterating through each items in cart
        foreach(WC()->cart->get_cart() as $cart_item){
            if($cart_item['product_id'] == $specific_product){
                $is_in_cart = true;
                break;
            }
        }
        if($is_in_cart)
            unset($available_gateways['inspire']);
    } else {
        unset($available_gateways['cod']);
    }
    return $available_gateways;
}

代码在您的活动子主题(或主题)的functions.php文件中或任何插件文件中。

此代码未经测试,但应该起作用……

我在功能末尾缺少返回语句。

return $available_gateways;

最新更新