在WooCommerce中为特定的产品类别添加费用,但仅当相关类别也存在时

我想为类别(A)添加费用,但仅当订单中有来自其他类别(B、C、D等)的产品时才计算费用。

但如果只订购A类产品,则不征收该税。

在我的代码中,在这两种情况下都会添加费用。你能指导我找到更好的解决方案吗?

我在我的网站上添加了以下代码:

add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 );
function custom_pcat_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Set HERE your categories (can be term IDs, slugs or names) in a coma separated array
    $categories = array('396');
    $fee_amount = 0;

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ){
        if( has_term( $categories, 'product_cat', $cart_item['product_id']) )
            $fee_amount = 20;
    }

    // Adding the fee
    if ( $fee_amount > 0 ){
        // Last argument is related to enable tax (true or false)
        WC()->cart->add_fee( __( "Taxa livrare ROPET", "woocommerce" ), $fee_amount, false );
    }
}

解决方案

您可以使用wp_get_post_terms()检索帖子的术语。当浏览购物车内容时,我们收集术语ID, 然后我们可以进行比较,以确定是否匹配。

使用的WordPress函数:

  • wp_get_post_terms()-检索帖子的术语

使用的PHP函数:

  • in_array()-检查数组中是否存在值
  • array_intersect()-计算数组的交集

因此您得到:

function action_woocommerce_cart_calculate_fees( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    
    // Only use term IDs
    $category_a = 15;
    $other_categories = array( 16, 17, 18 );
    
    // Fee amount
    $fee_amount = 20;
    
    // Initialize
    $term_ids = array();
    
    // Loop through cart contents
    foreach ( $cart->get_cart_contents() as $cart_item ) {      
        // Get product id
        $product_id = $cart_item['product_id'];
        
        // Retrieves the terms for a post.
        $terms = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'ids' ) );
        
        // Loop through
        foreach ( $terms as $term_id ) {
            // Checks if a value NOT exists in an array
            if ( ! in_array( $term_id, $term_ids ) ) {
                // Push
                $term_ids[] = $term_id;
            }   
        }
    }
    
    // Check for a specific category (A)
    if ( in_array( $category_a, $term_ids ) ) {
        // Check if ANY of the term ids exist
        if ( ! empty ( array_intersect( $other_categories, $term_ids ) ) ) {            
            // Last argument is related to enable tax (true or false)
            $cart->add_fee( __( 'Taxa livrare ROPET', 'woocommerce' ), $fee_amount, false );
        }
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );

相关文章