如何驗證客戶是否在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中文網其他相關文章!