檢查WooCommerce 中的購買歷史記錄
問題:
問題:您希望建立外掛程式為有購買歷史的客戶提供獨家優惠。挑戰在於確定用戶過去是否有進行過購買。
解決方案:
檢查客戶過去的購買function has_bought( $value = 0 ) { // Handling for registered users if ( is_numeric( $value) ) { // Use current user ID if not provided $meta_key = '_customer_user'; $meta_value = $value == 0 ? (int) get_current_user_id() : (int) $value; } // Handling for guest users else { $meta_key = '_billing_email'; $meta_value = sanitize_email( $value ); } global $wpdb; // Determine if any paid orders exist $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 true if at least one paid order exists 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>';
範例1: 檢查目前登入顧客的購買狀況
// Define the user 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>';
範例2: 檢查特定使用者ID 的購買狀況
// Define the billing email (string) $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中文網其他相關文章!