Set discount based on number of orders in WooCommerce

白昼怎懂夜的黑 提交于 2019-12-25 09:44:21

问题


In WooCommerce, how to set discount based on number of order?

For example I would like to apply a discount based on customer orders:

  • first order discount $50
  • second order discount $30
  • third order discount $10?

I've search internet but not found any solution or plugins available.

Thanks.


回答1:


Here is a custom function hooked in woocommerce_cart_calculate_fees that will add to cart a custom discount based on customer orders count, this way:

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

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

The only problem can be if customer is not logged in.

You may add, at the beginning, in first condition ! is_user_logged_in() this way:

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


来源:https://stackoverflow.com/questions/43084031/set-discount-based-on-number-of-orders-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!