如何在 WooCommerce 中根据产品类别和数量添加费用

How to add fees based on product categories and quantity in WooCommerce

我在 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);
        }
    }
}

但这并没有给出预期的结果。申请了费用但总额有误?你能帮忙弄清楚为什么不行吗?

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

  • 计算总数时,您没有考虑数量
  • 您添加费用的 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 );