Mostafa Dehghani Mostafa Dehghani - 2 months ago 16
PHP Question

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?



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

    $count = 0;
    $bought = false;

    // Get all customer orders
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        '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 status "completed"
    ) );

    // Going through each current customer orders
    foreach ( $customer_orders as $customer_order ) {

    // return "true" when customer has already one order
    if ( $count > 0 ) {
        $bought = true;
    return $bought;

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.