【问题标题】:How to add fees based on product categories and quantity in WooCommerce如何在 WooCommerce 中根据产品类别和数量添加费用
【发布时间】:2022-09-29 08:09:05
【问题描述】:

我在 WooCommerce 中有一些产品,分为两类:

Name: ORG Test
Slug: org-test

Name: ORG Prod
Slug: org-prod

如果产品与org-prod 类别匹配,我想计算每个数量的运费(每个数量 15 美元):

我的代码尝试:

add_action(\'woocommerce_cart_calculate_fees\', \'add_fees_on_ids\');
function add_fees_on_ids() {
    $total_act_fee = 0;
    $business_plan_exist = false;
    if (is_admin() && !defined(\'DOING_AJAX\')) {return;}
    foreach( WC()->cart->get_cart() as $cart_item ) {
        $product = $cart_item[\'data\'];
        $quantity = $cart_item[\'quantity\'];
        $categories = wc_get_product_category_list(  $product->get_id() );
        if (strstr($categories, \'org-prod\')) {
            $business_plan_exist = true;
            $total_act_fee = $total_act_fee + 15;
        }
        
        if ($business_plan_exist) {
            WC()->cart->add_fee(__(\'Shipping Fees \'), $total_act_fee);
        }
    }
}

但这并没有给出预期的结果。已收取费用,但总额有误?你能帮忙找出原因吗?

    标签: php wordpress woocommerce product fee


    【解决方案1】:

    您的代码包含一些错误和/或可以优化:

    • 在计算总数时,您没有考虑数量
    • 您添加费用的 if 条件位于您的 foreach 循环中,因此每个循环都会覆盖它
    • 没有必要使用WC()->cart,因为$cart 已经传递给回调函数
    • 使用has_term()wc_get_product_category_list()strstr()

    所以你得到:

    function action_woocommerce_cart_calculate_fees( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
        
        // Specific categories: the term name/term_id/slug. Several could be added, separated by a comma
        $categories = array( 'org-prod', 'categorie-1', 83 );
    
        // Initialize
        $total_act_fee = 0;
        $amount = 15;
         
        // Gets cart contents
        foreach ( $cart->get_cart_contents() as $cart_item ) {
            // Has certain category     
            if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
                // Get quantity
                $quantity = $cart_item['quantity'];
            
                // Addition to the total
                $total_act_fee += $amount * $quantity;
            }
        }
    
        // Greater than
        if ( $total_act_fee > 0 ) {
            // Add fee
            $cart->add_fee( __( 'Shipping Fees', 'woocommerce' ), $total_act_fee, true );
        }
    }
    add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
    

    【讨论】:

      【解决方案2】:

      希望以此为依托。

      @7uc1f3r 的解决方案似乎在用户端完美运行。但是,我们主要使用 woocommerce 之类的 POS 系统并在后端输入订单。有什么办法可以在后端进行这项工作?

      【讨论】:

        猜你喜欢
        • 2019-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多