WP SITES

3086 Coded Tutorials & 288 Plugins

Add WooCommerce Total Spent & Order Count To WP Users Table

This code adds custom columns for WooCommerce orders and total spent to the WordPress users table. This enables admins to quickly check and sort users by total spend and number of orders.

You can use the code in your child themes functions file or custom code snippets plugin.

// Add custom columns to the Users table
add_filter('manage_users_columns', 'add_woocommerce_user_columns');
function add_woocommerce_user_columns($columns) {
    $columns['total_spent'] = __('Total Spent', 'woocommerce');
    $columns['total_orders'] = __('Orders Total', 'woocommerce');
    return $columns;
}

// Populate the new columns with WooCommerce data
add_filter('manage_users_custom_column', 'populate_woocommerce_user_columns', 10, 3);
function populate_woocommerce_user_columns($value, $column_name, $user_id) {
    if ($column_name == 'total_spent') {
        $total_spent = wc_get_customer_total_spent($user_id);
        return wc_price($total_spent);
    }

    if ($column_name == 'total_orders') {
        $order_count = wc_get_customer_order_count($user_id);
        return $order_count;
    }

    return $value;
}

// Make the new columns sortable
add_filter('manage_users_sortable_columns', 'make_woocommerce_user_columns_sortable');
function make_woocommerce_user_columns_sortable($sortable_columns) {
    $sortable_columns['total_spent'] = 'total_spent';
    $sortable_columns['total_orders'] = 'total_orders';
    return $sortable_columns;
}

The code uses the WordPress manage_users_custom_column function with 2 WooCommerce functions to get the values for total_spent and total_orders :

  • wc_get_customer_total_spent
  • wc_get_customer_order_count

Leave a Reply

New Plugins