在WooCommerce中为特定的产品类别添加费用,但仅当相关类别也存在时 [英] Add a fee in WooCommerce for a specific product category, but only when related categories also present

查看:9
本文介绍了在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函数:

使用的PHP函数:

因此您得到:

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 );

这篇关于在WooCommerce中为特定的产品类别添加费用,但仅当相关类别也存在时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆