首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在WooCommerce中购买x个特定产品类别时,根据用户角色给予折扣

问在WooCommerce中购买x个特定产品类别时,根据用户角色给予折扣
EN

Stack Overflow用户
提问于 2021-10-31 11:29:00
回答 1查看 228关注 0票数 1

我想给我的客户为基础的用户角色的折扣:

如果用户从特定类别购买25种产品,用户角色

  • (订户) 50%的折扣。

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

代码语言:javascript
复制
// 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 );
}

有什么建议吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-31 20:18:46

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

当这等于25或更多,你可以申请折扣。

所以你得到了:

代码语言:javascript
复制
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 );
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69786450

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档