2016-08-16 21 views
2

我正在使用Woocommerce CSV導出插件。 我想要有一種方法來檢查客戶是否是新的,如果是,寫入訂單元數據爲定製meta-key a true
但是,如果用戶不是新的,什麼都不會發生。爲WooCommerce CSV導出插件添加自定義字段 - 客戶第一次訂購

我首先想到了WP用戶(user_registered)的創建日期。但我認爲有一個更好更快的方法。換句話說,我怎麼能知道這是一個客戶端的一階...

我的目標:如果該客戶訂購的第一次,有一個TRUE值,該順序導出CSV。

然後我試了to use this answer code沒有成功。

我的問題:
我怎麼能做到這一點?

感謝

+1

歡迎來到SO! SO不是「我需要這個;給我代碼」服務。那裏有搜索引擎。請提供一些您已經嘗試/遇到問題的代碼,以便獲得答案。 –

回答

2

基於this answer code(我最近做),它可能有一個將在數據庫中添加元的鍵/值wp_postmeta表爲新客戶第一順序的功能。因此,我們將改變一個位是有條件的功能是這樣的:

function new_customer_has_bought() { 

    $count = 0; 
    $new_customer = false; 

    // Get all customer orders 
    $customer_orders = get_posts(array(
     'numberposts' => -1, 
     'meta_key' => '_customer_user', 
     'meta_value' => get_current_user_id() 
    )); 

    // Going through each current customer orders 
    foreach ($customer_orders as $customer_order) { 
     $count++; 
    } 

    // return "true" when it is the first order for this customer 
    if ($count > 2) // or ($count == 1) 
     $new_customer = true; 

    return $new_customer; 
} 

此代碼放在你的活躍兒童主題或主題,或插件php文件的function.php文件。


使用情況THANKYOU HOOK:

add_action('woocommerce_thankyou', 'tracking_new_customer'); 
function tracking_new_customer($order_id) { 

    // Exit if no Order ID 
    if (! $order_id) { 
     return; 
    } 

    // The paid orders are changed to "completed" status 
    $order = wc_get_order($order_id); 
    $order->update_status('completed'); 

    // For 1st 'completed' costumer paid order status 
    if (new_customer_has_bought() && $order->has_status('completed')) 
    { 
     // Create 'first_order' custom field with 'true' value 
     update_post_meta($order_id, 'first_order', 'true'); needed) 
    } 
    else // For all other customer paid orders 
    { 
     // udpdate existing 'first_order' CF to '' value (empty) 
     update_post_meta($order_id, 'first_order', ''); 
    } 
} 

此代碼放在你的活躍兒童主題或主題的function.php文件,或者在一個插件PHP文件。

現在只爲第一個新客戶訂單你將有一個自定義元數據,關鍵'_first_customer_order'

要得到一個確定的順序ID這個這個值,你會使用這個(最後一個參數意味着它是一個字符串):

// Getting the value for a defined $order_id 
$first_customer_order = get_post_meta($order_id, 'first_order', false); 

// to display it 
echo $first_customer_order; 

所有的代碼進行測試和作品。


參考

+0

明天我會測試。謝謝你分享。 –

相關問題