在WooCommerce中隐藏基于产品类型的付款方式

Jef*_*f W 4 php wordpress product payment-gateway woocommerce

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

是我们发现的最接近但却没有做到我期待的事情.

是的,有插件可以做到这一点但我们希望在不使用其他插件的情况下实现这一点,并且不会使我们的样式表比现在更加噩梦.

对此有何帮助?

Loi*_*tec 9

这是一个在woocommerce_available_payment_gateways过滤器挂钩中使用自定义挂钩功能的示例,我可以根据购物车项目(产品类型)禁用付款网关:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

所有代码都在Woocommerce 3+上进行测试并且有效.

这只是向您展示事物如何运作的一个例子.你必须适应它