/**
* Snippet Name: Customer Order Count Column
* Snippet Author: coding-bunny.com
* Description: Adds a custom column in WooCommerce orders to show the total number of orders per customer based on their billing email.
*/
// Add filter to manage the custom columns in the shop orders list
add_filter( 'manage_edit-shop_order_columns', 'cb_add_order_count_column', 20 );
/**
* Add a custom column for customer order count.
*
* @param array $columns Existing columns.
* @return array Updated columns.
*/
function cb_add_order_count_column( $columns ) {
// Add the 'Total Customer Orders' column
$columns['email_order_count'] = __( 'Total Customer Orders', 'woocommerce' );
return $columns;
}
// Populate the custom column with the order count
add_action( 'manage_shop_order_posts_custom_column', 'cb_populate_order_count_column' );
/**
* Populate the custom column with the count of orders.
*
* @param string $column The name of the column.
*/
function cb_populate_order_count_column( $column ) {
global $post;
if ( 'email_order_count' === $column ) {
$billing_email = get_post_meta( $post->ID, '_billing_email', true );
if ( $billing_email ) {
// Get all orders for this customer
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_billing_email',
'meta_value' => $billing_email,
'post_type' => wc_get_order_types(),
'post_status' => array_keys( wc_get_order_statuses() ),
) );
$order_count = count( $customer_orders );
// If it's the customer's first order, display "First Order!"
if ( $order_count === 1 ) {
echo 'First Order!';
} else {
echo $order_count;
}
}
}
}
// Make the custom column sortable
add_filter( 'manage_edit-shop_order_sortable_columns', 'cb_make_order_count_column_sortable' );
/**
* Make the order count column sortable.
*
* @param array $sortable_columns Existing sortable columns.
* @return array Updated sortable columns.
*/
function cb_make_order_count_column_sortable( $sortable_columns ) {
$sortable_columns['email_order_count'] = 'email_order_count';
return $sortable_columns;
}
// Sort by the customer order count
add_action( 'pre_get_posts', 'cb_custom_order_count_column_sort' );
/**
* Sort the shop orders by the custom order count column.
*
* @param WP_Query $query The current query object.
*/
function cb_custom_order_count_column_sort( $query ) {
if ( ! is_admin() || ! $query->is_main_query() ) {
return;
}
$orderby = $query->get( 'orderby' );
if ( 'email_order_count' === $orderby ) {
$query->set( 'meta_key', '_billing_email' );
$query->set( 'orderby', 'meta_value' );
}
}
Customer Order Count Column
Adds a custom column in WooCommerce orders to show the total number of orders per customer based on their billing email.