这个函数是怎么工作的?
该函数的源码在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客户类中的一个方法,
/**
* 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 );
}
哪些状态的订单会计入用户总消费
使用这个函数可以干些什么
对于需要进行会员营销的网站,我们可以使用该函数获取用户的总消费金额。如果消费超过某个金额,我们可以将该用户视为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角色的任务。