根据WooCommerce中的订单数设置折扣 [英] Set discount based on number of orders in WooCommerce

查看:278
本文介绍了根据WooCommerce中的订单数设置折扣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

  • 第一笔折扣$ 50
  • 第二笔折扣$ 30
  • 第三笔优惠10美元?

我已经搜索了互联网,但未找到任何可用的解决方案或插件.

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

谢谢.

推荐答案

这是一个挂接到 woocommerce_cart_calculate_fees 的自定义函数,该函数将根据客户订单数向购物车添加自定义折扣:

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

该代码会出现在您活动的子主题(或主题)的function.php文件中,也可能会出现在任何插件文件中.

此代码已经过测试并且可以正常工作.

This code is tested and works.

唯一的问题可能是客户未登录.

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

您可以通过以下方式在开始时添加第一个条件! is_user_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;

这篇关于根据WooCommerce中的订单数设置折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆