当他们在 WooCommerce 中购买 x 数量的特定产品类别时,根据用户角色应用折扣

Apply discount based on user role when they buy x quantity of specific product category in WooCommerce

我想为基于客户的用户角色提供折扣,例如:

如果使用了一个片段,但它没有涵盖我问题的第二部分(来自特定类别的 25 个产品)。

// Applying conditionally a discount for a specific user role
add_action( 'woocommerce_cart_calculate_fees', 'discount_on_user_role', 20, 1 );
function discount_on_user_role( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return; // Exit

    // Only for 'company' user role
    if ( ! current_user_can('company') )
        return; // Exit

    // HERE define the percentage discount
    $percentage = 50;

    $discount = $cart->get_subtotal() * $percentage / 100; // Calculation

    // Applying discount
    $cart->add_fee( sprintf( __("Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
}

有什么建议吗?

对于类别 categorie-1(根据需要进行调整),您可以使用基于购物车中产品数量的计数器。

当等于或大于 25 时,您可以应用折扣。

所以你得到:

function action_woocommerce_cart_calculate_fees( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    
    // Only for 'company' user role
    if ( ! current_user_can( 'company' ) )
        return;
    
    // Category
    $category = 'categorie-1';

    // Percentage discount
    $percentage = 50; // 50%
    
    // Min quantity
    $minimun_quantity = 25;
    
    // Initialize
    $current_quantity = 0;
    $current_total = 0;

    // Loop though each cart item
    foreach ( $cart->get_cart() as $cart_item ) {
        // Has certain category     
        if ( has_term( $category, 'product_cat', $cart_item['product_id'] ) ) {
            // Get quantity
            $product_quantity = $cart_item['quantity'];

            // Add to quantity total
            $current_quantity += $product_quantity;
            
            // Get price
            $product_price = $cart_item['data']->get_price();
            
            // Add to current total
            $current_total += $product_price * $product_quantity;
        }
    }

    // Greater than or equal to
    if ( $current_quantity >= $minimun_quantity ) {
        // Calculation
        $discount = $current_total * $percentage / 100;

        // Applying discount
        $cart->add_fee( sprintf( __( 'Discount (%s)', 'woocommerce' ), $percentage . '%'), -$discount, true );     
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );