返回

在 WooCommerce 中针对过去三个月消费金额达标客户提供优惠

php

在 WooCommerce 中实施基于订单金额的优惠

问题

作为网店店主,你希望向在过去三个月内总消费金额达到或超过 350 欧元的忠实客户提供 50 欧元的优惠。然而,在你现有的 WooCommerce 设置中,尚未实现这一功能。

解决方法

要解决这个问题,可以使用以下自定义代码片段:

// 检查用户是否符合优惠资格
function check_eligibility_for_discount($user_id) {
    // 获取过去三个月的总消费金额
    $total_spent_last_three_months = get_user_meta($user_id, 'total_spent_last_three_months', true);

    if ($total_spent_last_three_months >= 350) {
        return true;
    } else {
        // 获取过去三个月的所有订单
        $orders = wc_get_orders(array(
            'customer' => $user_id,
            'date_query' => array(
                'after' => date('Y-m-d', strtotime('-3 months'))
            ),
            'status' => array('wc-completed') // 只考虑已完成的订单
        ));

        // 检查是否存在订单
        if (count($orders) > 0) {
            return false;
        } else {
            return true;
        }
    }
}

// 在购物车中应用优惠(如果符合资格)
function apply_discount_if_eligible($cart) {
    if (is_user_logged_in()) {
        $current_user = wp_get_current_user();
        $user_id = $current_user->ID;

        if (check_eligibility_for_discount($user_id)) {
            $discount_amount = 50;
            $cart->add_fee(__('Discount', 'your-text-domain'), -$discount_amount);
        }
    }
}

// 在订单完成时重置总消费金额
function reset_total_spent_after_order($order_id) {
    $order = wc_get_order($order_id);
    $user_id = $order->get_user_id();

    // 检查是否符合资格
    if (check_eligibility_for_discount($user_id)) {
        // 将总消费金额重置为 0
        update_user_meta($user_id, 'total_spent_last_three_months', 0);
    }
}

// 在订单完成时更新总消费金额
function update_total_spent_after_reset($user_id) {
    // 计算过去三个月的总消费金额
    $total_spent_last_three_months = 0;
    $orders = wc_get_orders(array(
        'customer' => $user_id,
        'date_query' => array(
            'after' => date('Y-m-d', strtotime('-3 months'))
        ),
        'status' => array('wc-completed')
    ));

    foreach ($orders as $order) {
        $total_spent_last_three_months += floatval($order->get_total());
    }

    // 更新总消费金额
    update_user_meta($user_id, 'total_spent_last_three_months', $total_spent_last_three_months);
}

如何使用?

将上述代码片段添加到你的 functions.php 文件或使用代码片段插件。此外,你需要创建一个名为 total_spent_last_three_months 的用户元数据字段,以存储用户的过去三个月总消费金额。

优势

  • 根据过去三个月的消费金额,准确识别符合优惠资格的客户。
  • 在应用优惠后自动重置总消费金额。
  • 考虑到有订单和无订单的情况。
  • 与 WooCommerce 的订单和购物车系统无缝集成。

结论

通过实施上述自定义代码,你可以为特定时间段内达到特定消费金额的客户提供基于订单金额的优惠。这是一种有效的方法来奖励忠实客户,并鼓励更多消费。

常见问题解答

1. 优惠的消费金额限制是多少?
它在代码片段中设置为了 350 欧元,但你可以根据需要调整这个值。

2. 该优惠可以与其他优惠同时使用吗?
否,此代码不会检查其他优惠,因此它可能会与其他优惠叠加使用。

3. 如何排除某些产品或类别?
你需要修改 apply_discount_if_eligible() 函数以检查排除的产品或类别。

4. 优惠只适用于已完成的订单吗?
是的,这个代码片段只考虑已完成的订单。

5. 过去三个月的总消费金额是如何计算的?
它基于订单的总金额(包括税费和运费),并且只考虑过去三个月内的订单。