Search code examples
phpwordpresswoocommerceproductorders

Checking if customer has already bought something in WooCommerce


I would like to create a WooCommerce plugin to add some offers for customers (that have a purchase History).

How can I check a user bought something before?

Thanks.


Solution

  • Update 2020: New updated improved, light and faster version HERE that handle also guests from billing email


    Yes it is possible creating a conditional function that return true when a customer has already at least one order with status completed.

    Here is the code for this conditional function:

    function has_bought() {
        // Get all customer orders
        $customer_orders = get_posts( array(
            'numberposts' => 1, // one order is enough
            'meta_key'    => '_customer_user',
            'meta_value'  => get_current_user_id(),
            'post_type'   => 'shop_order', // WC orders post type
            'post_status' => 'wc-completed', // Only orders with "completed" status
            'fields'      => 'ids', // Return Ids "completed"
        ) );
    
        // return "true" when customer has already at least one order (false if not)
       return count($customer_orders) > 0 ? true : false; 
    }
    

    This code is tested and works.

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


    USAGE (as a condition):

    • You can use it in some WooCommerce templates that you will have previously copied to your active child theme or theme.
    • In your theme php files.
    • In plugin php files.
    • Any php function or WordPress/WooCommerce.

    References