如何获取WooCommerce商城客户消费总额

将用户升级为某个会员级别,以享受会员优惠,是营销中常见的策略。在WooCommerce中,我们可以使用wc_get_customer_total_spent函数来方便地获取用户的总消费金额。需要传入用户的ID作为该函数的唯一参数,函数将返回用户的总消费金额字符串。

这个函数是怎么工作的?

该函数的源码在woocommerceincludeswc-user-functions.php 文件中,代码详情如下:

/**
 * Get total spent by customer.
 *
 * @param  int $user_id User ID.
 * @return string
 */
function wc_get_customer_total_spent( $user_id ) {
	$customer = new WC_Customer( $user_id );
	return $customer->get_total_spent();
}

上面代码中的 get_total_spent 方法是WooCommerce客户类中的一个方法,

在该方法中,程序首先检查用户自定义字段中是否存在 _money_spent 字段。如果存在,则直接返回该字段的值;如果不存在,则查询数据库获取用户的总消费金额,并将其保存到用户自定义字段中。从程序执行时间的角度来看,获取用户自定义字段要比直接查询用户消费记录得到总消费金额快得多。这是一种缓存方法,在开发主题和插件时可以参考使用。

/**
 * Return how much money this customer has spent.
 *
 * @since 3.0.0
 * @param WC_Customer $customer Customer object.
 * @return float
 */
public function get_total_spent( &$customer ) {
	$spent = apply_filters(
		'woocommerce_customer_get_total_spent',
		get_user_meta( $customer->get_id(), '_money_spent', true ),
		$customer
	);
	if ( '' === $spent ) {
		global $wpdb;
		$statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() );
		$spent    = $wpdb->get_var(
			// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared
			apply_filters(
				'woocommerce_customer_get_total_spent_query',
				"SELECT SUM(meta2.meta_value)
				FROM $wpdb->posts as posts
				LEFT JOIN {$wpdb->postmeta} AS meta ON posts.ID = meta.post_id
				LEFT JOIN {$wpdb->postmeta} AS meta2 ON posts.ID = meta2.post_id
				WHERE   meta.meta_key       = '_customer_user'
				AND     meta.meta_value     = '" . esc_sql( $customer->get_id() ) . "'
				AND     posts.post_type     = 'shop_order'
				AND     posts.post_status   IN ( 'wc-" . implode( "','wc-", $statuses ) . "' )
				AND     meta2.meta_key      = '_order_total'",
				$customer
			)
			// phpcs:enable
		);
		if ( ! $spent ) {
			$spent = 0;
		}
		update_user_meta( $customer->get_id(), '_money_spent', $spent );
	}
	return wc_format_decimal( $spent, 2 );
}

哪些状态的订单会计入用户总消费

根据WooCommerce的默认设置,只有处于“处理中”或“已完成”状态的订单才会被纳入用户的总消费金额。如果需要更改计入总消费的订单状态,我们可以使用woocommerce_order_is_paid_statuses Filter 进行修改。

使用这个函数可以干些什么

对于需要进行会员营销的网站,我们可以使用该函数获取用户的总消费金额。如果消费超过某个金额,我们可以将该用户视为VIP用户,并允许他享受一些普通用户无法享受的特权,例如购买只有VIP用户才能购买的商品。下面的示例代码中,如果用户的总消费超过500元,我们将在用户的账户页面上显示一条消息,提醒用户他是我们的VIP会员,可以购买VIP限定的商品。

add_action('woocommerce_account_dashboard', function ()
{
    $user_id = get_current_user_id();
    if (wc_get_customer_total_spent($user_id) > 500) {
        echo '<div class="woocommerce-message"><a class="button" href="/shop/vip">查看VIP特定商品</a>恭喜,您是我们尊贵的VIP。</div>';
    }
});

在数据库层面获取用户总消费金额可能是一个比较耗费资源的操作,对于流量较大的网站,我们可以通过调整用户角色来减少这个操作,然后设置定时任务,在网站空闲时每天处理升级用户VIP角色的任务。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注