根据WooCommerce中的产品类型隐藏付款方式



在WoCommerce中,我想禁用特定的付款方式,并显示WooCommerce中订阅产品的特定付款方式(反之亦然)。

这是我们发现的最接近的事情,但没有做我期望的。

是的,有些插件可以做到这一点,但是我们希望无需使用其他插件就可以实现此目标,而不会使我们的样式表的噩梦比以前更多。

请为此提供任何帮助?

这是一个示例,在 woocommerce_available_payment_gateways filter Hook中具有自定义钩函数,我可以根据购物车项目(产品类型)禁用付款网关:

add_filter('woocommerce_available_payment_gateways', 'conditional_payment_gateways', 10, 1);
function conditional_payment_gateways( $available_gateways ) {
    // Not in backend (admin)
    if( is_admin() ) 
        return $available_gateways;
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $prod_variable = $prod_simple = $prod_subscription = false;
        // Get the WC_Product object
        $product = wc_get_product($cart_item['product_id']);
        // Get the product types in cart (example)
        if($product->is_type('simple')) $prod_simple = true;
        if($product->is_type('variable')) $prod_variable = true;
        if($product->is_type('subscription')) $prod_subscription = true;
    }
    // Remove Cash on delivery (cod) payment gateway for simple products
    if($prod_simple)
        unset($available_gateways['cod']); // unset 'cod'
    // Remove Paypal (paypal) payment gateway for variable products
    if($prod_variable)
        unset($available_gateways['paypal']); // unset 'paypal'
    // Remove Bank wire (Bacs) payment gateway for subscription products
    if($prod_subscription)
        unset($available_gateways['bacs']); // unset 'bacs'
    return $available_gateways;
}

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

所有代码均在WooCommerce 3 上进行测试。

这只是向您展示如何工作的一个例子。您将不得不适应

此代码对我非常有用,但是我必须修复一个错误:行

 $prod_variable = $prod_simple = $prod_subscription = false;

必须放在外面(之前),否则每次执行新项目时都会重置标志。我的情况是,每当订阅产品都在购物车上时,我都需要解开特定的付款方式。实际上,只有只有一个订阅产品,此代码才能正常工作。如果我将另一个不同的物品放在购物车上,则标志将再次转为False,并且付款方式将加载。将线路放在foreach之外将解决此问题。

最新更新