如何验证客户是否在 WooCommerce 中进行了购买
在 WooCommerce 中,向以前购买过的忠实客户提供激励是一种常见做法。为了有效实施此类策略,有必要验证客户之前是否进行过任何购买。
检查购买历史记录
为了确定客户的购买历史记录,WooCommerce 提供一个名为 has_bought() 的轻量且高效的条件函数。此函数分析客户数据以确定他们之前是否进行过购买。
该函数同时处理注册用户和访客:
实现该函数
function has_bought( $value = 0 ) { if ( ! is_user_logged_in() && $value === 0 ) { return false; } global $wpdb; // Based on user ID (registered users) if ( is_numeric( $value) ) { $meta_key = '_customer_user'; $meta_value = $value == 0 ? (int) get_current_user_id() : (int) $value; } // Based on billing email (Guest users) else { $meta_key = '_billing_email'; $meta_value = sanitize_email( $value ); } $paid_order_statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() ); $count = $wpdb->get_var( $wpdb->prepare(" SELECT COUNT(p.ID) FROM {$wpdb->prefix}posts AS p INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $paid_order_statuses ) . "' ) AND p.post_type LIKE 'shop_order' AND pm.meta_key = '%s' AND pm.meta_value = %s LIMIT 1 ", $meta_key, $meta_value ) ); // Return a boolean value based on orders count return $count > 0; }
用法示例
登录客户:
if( has_bought() ) echo '<p>You have already made a purchase</p>'; else echo '<p>Welcome, for your first purchase you will get a discount of 10%</p>';
拥有帐单电子邮件的客人:
$email = '[email protected]'; if( has_bought( $email ) ) echo '<p>customer have already made a purchase</p>'; else echo '<p>Customer with 0 purchases</p>'
以上是如何确定客户是否在 WooCommerce 中进行了购买?的详细内容。更多信息请关注PHP中文网其他相关文章!