Display customer order count

Trusitio Support

You are here:
< Back

There are several reasons you might want to get all WooCommerce orders for a customer in your shop. For example, you may want to find out if they’ve ever purchased a product, or do something as simple as count the number of orders they’ve placed with you.

Since orders are a custom post type, you can use get_posts to query orders, which is a pretty standard WP query that most developers are familiar with and can use.

function wc_get_customer_orders() {

// Get all customer orders
$customer_orders = get_posts( array(
'numberposts' =&gt; -1,
'meta_key' =&gt; '_customer_user',
'meta_value' =&gt; get_current_user_id(),
'post_type' =&gt; wc_get_order_types(),
'post_status' =&gt; array_keys( wc_get_order_statuses() ),
) );

$customer = wp_get_current_user();

// Order count for a "loyal" customer
$loyal_count = 5;

// Text for our "thanks for loyalty" message
$notice_text = sprintf( 'Hey %1$s ???? We noticed you\'ve placed more than %2$s orders with us – thanks for being a loyal customer!', $customer-&gt;display_name, $loyal_count );

// Display our notice if the customer has at least 5 orders
if ( count( $customer_orders ) &gt;= $loyal_count ) {
wc_print_notice( $notice_text, 'notice' );
}
}
add_action( 'woocommerce_before_my_account', 'wc_get_customer_orders' );

The result should display like this on your Woocommerce main order display dashboard