在 WooCommerce 中檢查客戶購買歷史記錄
在 WooCommerce 中,通常需要確定客戶之前是否進行過任何購買。此資訊可用於根據購買歷史記錄提供個人化折扣、獎勵或其他促銷活動。
解決方案
以下函數 has_bought() 有效檢查是否給定客戶在 WooCommerce中有任何已付款訂單:
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>';
檢查特定用戶ID:
$user_id = 85; if( has_bought( $user_id ) ) echo '<p>customer have already made a purchase</p>'; else echo '<p>Customer with 0 purchases</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 3 上進行了測試,並且也應該適用於早期版本。
以上是如何檢查客戶之前是否在 WooCommerce 中購買過?的詳細內容。更多資訊請關注PHP中文網其他相關文章!