所有分类
  • 所有分类
  • 其它

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角色的任务。

显示验证码

社交账号快速登录