【问题标题】:Set zero tax class to specific item count from defined product categories in Woocommerce将零税级设置为 Woocommerce 中定义的产品类别中的特定项目计数
【发布时间】:2020-09-18 10:04:25
【问题描述】:

在 WooCommerce 中,如果购物车包含来自 2 个特定类别的 6 个或更多商品,那么我想仅为这些商品(而不是整个购物车)设置一个特定的税级(零税),所以不要为其他产品)。

我使用这段代码计算购物车中来自 2 个类别的商品数量,但我找不到如何完成它以便将它们设置为我的“零税”税级。

add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_taxes', 20, 1 );
function apply_conditionally_taxes( $cart ){

    $item_count   = $cart->get_cart_contents_count();
    $kingcat_count = 0;

    foreach ( $cart->get_cart() as $cart_item ) {
        if ( has_term( 'patisseries', 'product_cat', $cart_item['product_id'] ) or has_term( 'viennoiseries-et-gaufres', 'product_cat', $cart_item['product_id'] ) ) {
            $kingcat_count += $cart_item['quantity'];
            //echo $kingcat_count; 
        }

    }
}

【问题讨论】:

    标签: php wordpress woocommerce cart tax


    【解决方案1】:

    代码包含:(作为注释添加到代码中的解释)

    • 只统计属于某个类别的项目
    • 仅为这些项目设置特定的税级
    function action_woocommerce_before_calculate_totals( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
    
        /* SETTINGS */
    
        // Set categories
        $categories = array ( 'patisseries', 'viennoiseries-et-gaufres' );
    
        // Contains 6 or more items
        $contains_min = 6;
    
        /* END SETTINGS */
    
        // Counter
        $counter = 0;
    
        // Loop trough
        foreach ( $cart->get_cart() as $cart_item ) {
            // Break loop
            if ( $counter >= $contains_min ) {
                break;
            }
    
            // Has term
            if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
                // Add to counter
                $counter += $cart_item['quantity'];
            }
        }
    
        // Check
        if ( $counter >= $contains_min ) {
            // Loop trough
            foreach( $cart->get_cart() as $cart_item ) {
                // Has term
                if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
                    // We set "Zero rate" tax class
                    $cart_item['data']->set_tax_class( 'Zero rate' );
                }
            }
        }
    }   
    add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 2017-06-30
      • 1970-01-01
      • 2018-01-30
      • 2020-05-09
      • 1970-01-01
      • 2016-07-16
      相关资源
      最近更新 更多