【问题标题】:Set discount based on number of orders in WooCommerce根据 WooCommerce 中的订单数量设置折扣
【发布时间】:2017-03-29 03:57:27
【问题描述】:

在 WooCommerce 中,如何根据订单数量设置折扣?

例如,我想根据客户订单应用折扣:

  • 首单优惠50美元
  • 二单优惠$30
  • 三单优惠$10?

我搜索了互联网,但没有找到任何可用的解决方案或插件。

谢谢。

【问题讨论】:

    标签: php wordpress woocommerce orders discount


    【解决方案1】:

    这是一个挂在 woocommerce_cart_calculate_fees 中的自定义函数,它会根据客户订单数向购物车添加自定义折扣,这样:

    add_action('woocommerce_cart_calculate_fees' , 'discount_based_on_customer_orders', 10, 1);
    function discount_based_on_customer_orders( $cart_object ){
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;  
    
        // Getting "completed" customer orders
        $customer_orders = get_posts( array(
            'numberposts' => -1,
            'meta_key'    => '_customer_user',
            'meta_value'  => get_current_user_id(),
            'post_type'   => 'shop_order', // WC orders post type
            'post_status' => 'wc-completed' // Only orders with status "completed"
        ) );
    
        // Orders count
        $customer_orders_count = count($customer_orders);
    
        // The cart total
        $cart_total = WC()->cart->get_total(); // or WC()->cart->get_total_ex_tax()
    
        // First customer order
        if( empty($customer_orders) || $customer_orders_count == 0 ){
            $discount_text = __('First Order Discount', 'woocommerce');
            $discount = -50;
        } 
        // 2nd orders discount
        elseif( $customer_orders_count == 1 ){
            $discount_text = __('2nd Order Discount', 'woocommerce');
            $discount = -30;            
        } 
        // 3rd orders discount
        elseif( $customer_orders_count == 2 ){
            $discount_text = __('3rd Order Discount', 'woocommerce');   
            $discount = -10;        
        }
    
        // Apply discount
        if( ! empty( $discount ) ){
            // Note: Last argument is related to applying the tax (false by default)
            $cart_object->add_fee( $discount_text, $discount, false);
        }
    }
    

    代码位于您的活动子主题(或主题)的 function.php 文件中或任何插件文件中。

    此代码已经过测试并且可以工作。

    唯一的问题可能是客户没有登录。

    您可以在开头添加! is_user_logged_in() 这样的第一个条件:

        if ( is_admin() && ! defined( 'DOING_AJAX' ) && ! is_user_logged_in() )
            return;
    

    【讨论】:

    • 嗨,如果使用优惠券,您知道如何禁用此功能吗?
    • @LoicTheAztec 可以打折吗?
    猜你喜欢
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多