Jean-Francois Tellier Jean-Francois Tellier - 2 months ago 5x
PHP Question

Add custom field for WooCommerce CSV Export plugin - For customer first order

I'm using Woocommerce CSV Export plugin.
I will like to have a way to check if the customer is NEW and if it is, to write in order metadata for a custom


But if user is not New, nothing will happen.

I thought first to start with the creation date of the WP user (user_registered). But I think there is a better and faster way. In other words, how can I know if this is the first order of a client...

My goal: If this customer is ordering for the first time, have a
value, for this order in the Export CSV.

Then I have tried to use this answer code without success.

My question:

How could I achieve this?



Based on this answer code (I have recently made), it's possible to have a function that will add a meta key/value in the database wp_postmeta table for a New customer first order. So we will change a bit that conditional function this way:

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 ) {

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

    return $new_customer;

This code goes in function.php file of your active child theme or theme, or in a plugin php file.


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

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

    // 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', '' );

This code goes in function.php file of your active child theme or theme, or in a plugin php file.

Now only for the FIRST new customer order you will have a custom meta data which key is '_first_customer_order' and value is true.

To get this this value for a defined order ID, you will use this (last argument means it's a string):

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

All the code is tested and works.