WooCommerce: Get Total Sales By Product Category

It’s easy enough in WooCommerce to get/calculate product sales. What’s difficult, on the other hand, is calculating the total amount of sales for a specific category, because there is no core function that already does that.

Why sales by category – you may ask? Well, to me, that’s a very important metric. For example, I sell both consulting and non-consulting products on this same website, so it’s important for me to keep track of category sales year-on-year, especially when my goal is reducing 1-to-1 client work while increasing scalable product sales such as courses, plugins and memberships.

In this quick tutorial, we will first get the “WooCommerce orders that contain a target product category”, and after that we will loop through the array to calculate the total sales for that specific category. Sounds difficult? No worries – just copy and paste the snippets below.

Pity that the product categories dashboard page doesn’t give you an idea of the total spent by category… let’s find a way to calculate that! You can then print the total where you wish: on the frontend single product category page in case that can help customers, or in the backend, for example in the single product category edit page!

PHP Snippet: Get Total Purchase Amount For a Specific WooCommerce Product Category

/**
 * @snippet       Calculate Product Category Sales Amount
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 7
 * @community     https://businessbloomer.com/club/
 */

// 1. ORDERS GETTER

function bbloomer_get_orders_by_product_cat( $cat_slug, $order_status = array( 'wc-completed' ) ) {
    global $wpdb;
	 $args = array(
		 'limit' => -1,
	 	 'status' => 'publish',
		 'return' => 'ids',
		 'category' => array( $cat_slug ),
	 );
	 $product_ids = wc_get_products( $args );
    $results = $wpdb->get_col( "
        SELECT order_items.order_id
        FROM {$wpdb->prefix}woocommerce_order_items as order_items
        LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
        LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
        WHERE posts.post_type = 'shop_order'
        AND posts.post_status IN ( '" . implode( "','", $order_status ) . "' )
        AND order_items.order_item_type = 'line_item'
        AND order_item_meta.meta_key = '_product_id'
        AND order_item_meta.meta_value IN ( '" . implode( "','", $product_ids ) . "' )
    " );
    return $results;
}

// 2. SALES CALCULATOR

function bbloomer_cat_sales( $cat_slug ) {
	$orders = bbloomer_get_orders_by_product_cat( $cat_slug );
	$total = 0;
	foreach ( $orders as $order_id ) {
		foreach ( wc_get_order( $order_id )->get_items() as $key => $item ) {
			$product_id = $item->get_product_id();
			if ( ! $product_id ) continue;
			if ( has_term( $cat_slug, 'product_cat', $product_id ) ) $total += $item->get_total();
		}
	}
   return wc_price( $total );
}

// 3. USAGE
// E.G. YOU COULD PLACE THIS IN THE BACKEND OF FRONTEND:

echo bbloomer_cat_sales( 'tables' );

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Exclude Category from ‘product_categories’ Shortcode
    Sometimes solutions are very simple, and you don’t need rocket science to fix your issue! A client of mine needed to hide a category from the Product Categories Shortcode ( WooCommerce Mini-Plugins (30) ); in fact, there is no parameter that allows you to “exclude” a given product category such as “uncategorized” or whatever category […]
  • WooCommerce: Hide Products From Specific Category @ Shop
    A very handy snippet. Sometimes, you only want to show certain categories on the shop page, and have those products ONLY show under the category archive instead.
  • WooCommerce: “Sale” Category (Automatic)
    You can use a shortcode or block in order to display the WooCommerce products on sale. However, what if you wanted a proper “product category” called “Sale” – and where you didn’t need to manually assign this category to each product? Basically, how do we display all the discounted products in a custom category called […]
  • WooCommerce: Display Product Categories @ Cart & Checkout Pages
    While working for a freelance client I had to “detect” the cart item categories in order to apply some PHP customization. So I thought – why not share with you how to display product categories in the Cart and Checkout? This adds a nice touch to those two vital pages, and prints a list of […]
  • WooCommerce: Edit “Add to Cart” Text by Product Category
    Today we take a look at the WooCommerce “Add to Cart” buttons. What if you wanted to change the “Add to Cart” text depending on the Product Category? For example, you may want to show “Buy Now” for books and “Add to Basket” for cds.

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

4 thoughts on “WooCommerce: Get Total Sales By Product Category

  1. This code not providing correct total sales for one particular category

    1. It only counts “completed” orders, maybe that’s the issue?

      1. No, I have tested woo-commerce analytics reports only for completed orders, the above code given amount and analytics amount have big mis match

        1. It could be a WooCommerce Analytics sync problem, too! Lol. Anyway, it’s difficult to say without taking a look at your website backend. My code works on my test website so not sure I’m afraid

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *