为给定顶级类别的所有子类别禁用特定的 WooCommerce 付款方式

问题描述

我正在尝试通过 WooCommerce 的给定类别 slug 停用所有子类别的 PayPal。目前我的以下代码只是停用了一个类别的付款方式。是否可以停用所有子类别?

slice

解决方法

更新 2

要为顶级产品类别的子类别禁用特定支付网关,请使用以下命令:

add_filter( 'woocommerce_available_payment_gateways','disable_payment_gateway_subcategory' );
function disable_payment_gateway_subcategory( $payment_gateways ) {
    if ( is_admin() ) return $payment_gateways; // Not on admin

    $taxonomy     = 'product_cat';
    $term_slug    = 'tobacco'; // Main top category
    $term_id      = get_term_by( 'slug',$term_slug,$taxonomy )->term_id; // get term Id
    $children_ids = get_term_children( $term_id,$taxonomy ); // Get all children terms Ids
    array_unshift( $children_ids,$term_id ); // Adding main term Id to the array

    // Check each cart item for given subcategories of a top category
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $term_ids = wp_get_post_terms( $cart_item['product_id'],$taxonomy,array('fields' => 'ids') );

        if ( array_intersect( $children_ids,$term_ids ) ) {
            unset($payment_gateways['ppec_paypal']);
            break; // stop the loop
        }
    }
    return $payment_gateways;
}

代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。

,

对于有同样问题的其他人。 @LoicTheAztec 代码由代码部分扩展,以检查单个产品站点是否也是该类别的一部分:

 * Disable payment gateway based on category.
 */
add_filter( 'woocommerce_available_payment_gateways',$term_id ); // Adding main term Id to the array

    // Check on single product site 
    $cateID = wp_get_post_terms( get_the_ID(),array('fields' => 'ids') );
    if ( array_intersect( $children_ids,$cateID ) ) {
        unset($payment_gateways['ppec_paypal']);
    }

    // Check each cart item for given subcategories of a top category
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $term_ids = wp_get_post_terms( $cart_item['product_id'],$term_ids ) ) {
            unset($payment_gateways['ppec_paypal']);
            break; // stop the loop
        }
    }
    return $payment_gateways;
        
}