首頁 >後端開發 >php教程 >如何確定 WooCommerce 客戶是否有購買歷史記錄?

如何確定 WooCommerce 客戶是否有購買歷史記錄?

Patricia Arquette
Patricia Arquette原創
2024-11-13 13:09:02972瀏覽

How to Determine if a WooCommerce Customer Has a Purchase History?

確定客戶在 WooCommerce 中的購買歷史

開發 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;
}

用法範例

1.檢查註冊用戶購買情況:

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>';

2.根據帳單電子郵件檢查來賓用戶購買狀況:

// Define the billing email (string)
$email = '[email&#160;protected]';

if( has_bought( $email ) )
        echo '<p>customer have already made a purchase</p>';
    else
        echo '<p>Customer with 0 purchases</p>'

透過使用此功能,插件開發人員可以輕鬆確定客戶在WooCommerce 中是否有購買歷史記錄,從而為增強的客戶提供有針對性的促銷和折扣訂婚。

以上是如何確定 WooCommerce 客戶是否有購買歷史記錄?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn