WooCommerce: Calculate Sales by State

You’re filling out your tax reports… and then find out WooCommerce doesn’t give you this calculation by default!

Don’t cry πŸ™‚ Today I’ll show you a quick snippet to calculate that in a second. Feel free to change the year, the country and the states in the snippet.

WooCommerce: get sales by state

PHP Snippet: Get Sales by State @ WooCommerce Admin (Reports)

/**
 * @snippet       Get Sales by State @ WooCommerce Admin
 * @how-to        Get CustomizeWoo.com FREE
 * @sourcecode    https://businessbloomer.com/?p=72853
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 3.1.2
 */

// -----------------------
// 1. Create extra tab under Reports / Orders

add_filter( 'woocommerce_admin_reports', 'bbloomer_admin_add_report_orders_tab' );

function bbloomer_admin_add_report_orders_tab( $reports ) { 

$array = array(
    'sales_by_state' => array(
        'title' => 'Sales by state',
        'description' => '',
        'hide_title' => 1,
        'callback' => 'bbloomer_yearly_sales_by_state'
    )
);

$reports['orders']['reports'] = array_merge($reports['orders']['reports'],$array);

return $reports; 
}

// -----------------------
// 2. Calculate sales by state

function bbloomer_yearly_sales_by_state() {

	$year = 2017; // change this if needed
	$total_ca = $total_wa = 0; // add states if needed

    $args = [
        'post_type' => 'shop_order',
        'posts_per_page' => '-1',
		'year' => $year,
        'post_status' => ['wc-completed']
    ];
    $my_query = new WP_Query($args);
    $orders = $my_query->posts;

    foreach ($orders as $order => $value) {
   
	$order_id = $value->ID;
	$order = wc_get_order($order_id);
	$order_data = $order->get_data();

	if ( $order_data['billing']['country'] === 'US' ) {   
		if ( $order_data['billing']['state'] === 'CA' ) $total_ca += $order->get_total();
		if ( $order_data['billing']['state'] === 'WA' ) $total_wa += $order->get_total();
	}

    }

	echo "<h3>Sales by State for Year " . $year . "</h3>";
	echo "CA: " . wc_price($total_ca) . "</br>";
	echo "WA: " . wc_price($total_wa) . "</br>";

}

Where to add this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (delete "?>" if you have it there). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such files - if you need more guidance, please take a look at my free video tutorial "Where to Place WooCommerce Customization?"

Does this snippet (still) work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting on PHP 7.3.

If you think this code saved you time & money, feel free to join 14,000+ WooCommerce Weekly subscribers for blog post updates or 250+ Business Bloomer supporters for 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce?

Check out these free video tutorials. You can learn how to customize WooCommerce without unnecessary plugins, how to properly configure the WooCommerce plugin settings and even how to master WooCommerce troubleshooting in case of a bug!

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.

33 thoughts on “WooCommerce: Calculate Sales by State

  1. Don’t know how everyone got it to work. As a newbie, I don’t know where to put this code. I followed the video link which led me to an account creation page. Added details, got an email created logged in, and reset the password. Now What? I can see that there is an order created but cannot open that video. If I come back here and click the video link again, It is asking again to create an account.

    I am sure the provided code works very well but it is of no use for a newbie.

    BTW I am not looking for pointers on where to put the code, I am just bringing up the workflow of this article/site.

    1. Thanks for your feedback! I’ve revised the sign-up process, try again and let me know

  2. Is it possible to add Sales by State as the first tab? Before Sales by date?

    1. Hi, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  3. I updated Fred D.’s code to include some line breaks for list of states, and also to edit the html code that got inserted in his post.

    /**
     * @snippet       Get Sales by State @ WooCommerce Admin
     * @how-to        Get CustomizeWoo.com FREE
     * @sourcecode    https://businessbloomer.com/?p=72853
     * @author        Rodolfo Melogli, update by Fred D.
     * @testedwith    WooCommerce 3.1.2
     */
     
    // -----------------------
    // 1. Create extra tab under Reports / Orders
     
    add_filter( 'woocommerce_admin_reports', 'bbloomer_admin_add_report_orders_tab' );
     
    function bbloomer_admin_add_report_orders_tab( $reports ) { 
     
    $array = array(
        'sales_by_state' => array(
            'title' => 'Sales by state',
            'description' => '',
            'hide_title' => 1,
            'callback' => 'bbloomer_yearly_sales_by_state'
        )
    );
     
    $reports['orders']['reports'] = array_merge($reports['orders']['reports'],$array);
     
    return $reports; 
    }
     
    // -----------------------
    // 2. Calculate sales by state
    
    function bbloomer_yearly_sales_by_state() {
     
        $year = 2019; // change this if needed
        $total_ca = $total_wa = 0; // add states if needed
     
        $args = [
            'post_type' => 'shop_order',
            'posts_per_page' => '-1',
            'year' => $year,
            'post_status' => ['wc-completed']
        ];
        $my_query = new WP_Query($args);
        $orders = $my_query->posts;
     
        $usArr = array();
        $caArr = array();
        $mxArr = array();
        //$salesArr = array();
         
        $usTotal = 0;
        $caTotal = 0;
        $mxTotal = 0;
             
        foreach ($orders as $order => $value) 
        {
            $order_id = $value->ID;
            $order = wc_get_order($order_id);
            $order_data = $order->get_data();
             
            if ( $order_data['billing']['country'] === 'US' ) {
                $myTotal = $order->get_total();
                $usTotal += $myTotal;
                $usArr[$order_data['billing']['state']] += $myTotal;
            }
             
            if ( $order_data['billing']['country'] === 'CA' ) {
                $myTotal = $order->get_total();
                $caTotal += $myTotal;
                $caArr[$order_data['billing']['state']] += $myTotal;
            }
             
            if ( $order_data['billing']['country'] === 'MX' ) {
                $myTotal = $order->get_total();
                $mxTotal += $myTotal;
                $mxArr[$order_data['billing']['state']] += $myTotal;
            }
        }
     
        arsort($usArr);
        arsort($caArr);
        arsort($mxArr);
         
        echo "Sales by State for Year " . $year . " for the USA:<br>";
        foreach($usArr as $usState => $usSalesValue)       
        {
            echo $usState . ": " . wc_price($usSalesValue) . "<br>";
             
        }
        echo "Total US Sales: " . $usTotal; 
        echo "</p>";    
         
        echo "Sales by Province for Year " . $year . " for Canada:<br>";
        foreach($caArr as $caState => $caSalesValue)       
        {
            echo $caState . ": " . wc_price($caSalesValue) . "<br>";
             
        }
        echo "Total Canada Sales: " . $caTotal; 
        echo "</p>";
     
        echo "Sales by State for Year " . $year . " for Mexico:<br>";
        foreach($mxArr as $mxState => $mxSalesValue)       
        {
            echo $mxState . ": " . wc_price($mxSalesValue) . "<br>";
             
        }
        echo "Total Mexico Sales: " . $mxTotal; 
        echo "</p>";
     
     
    }
    
    1. Nice!

  4. Cool, thank you!
    I updated it a bit to make it dynamically build out the states. Could modify a bit more to automatically do the countries too, but this was all I needed for now. Hope it helps:

    function bbloomer_yearly_sales_by_state() {
    
        $year = 2019; // change this if needed
        $total_ca = $total_wa = 0; // add states if needed
    
        $args = [
            'post_type' =&gt; 'shop_order',
            'posts_per_page' =&gt; '-1',
            'year' =&gt; $year,
            'post_status' =&gt; ['wc-completed']
        ];
        $my_query = new WP_Query($args);
        $orders = $my_query-&gt;posts;
    
        $usArr = array();
        $caArr = array();
        $mxArr = array();
        //$salesArr = array();
        
        $usTotal = 0;
        $caTotal = 0;
        $mxTotal = 0;
            
        foreach ($orders as $order =&gt; $value) 
        {
            $order_id = $value-&gt;ID;
            $order = wc_get_order($order_id);
            $order_data = $order-&gt;get_data();
            
            if ( $order_data['billing']['country'] === 'US' ) {
                $myTotal = $order-&gt;get_total();
                $usTotal += $myTotal;
                $usArr[$order_data['billing']['state']] += $myTotal;
            }
            
            if ( $order_data['billing']['country'] === 'CA' ) {
                $myTotal = $order-&gt;get_total();
                $caTotal += $myTotal;
                $caArr[$order_data['billing']['state']] += $myTotal;
            }
            
            if ( $order_data['billing']['country'] === 'MX' ) {
                $myTotal = $order-&gt;get_total();
                $mxTotal += $myTotal;
                $mxArr[$order_data['billing']['state']] += $myTotal;
            }
        }
    
        arsort($usArr);
        arsort($caArr);
        arsort($mxArr);
        
        echo "Sales by State for Year " . $year . " for the USA:";
        foreach($usArr as $usState =&gt; $usSalesValue)       
        {
            echo $usState . ": " . wc_price($usSalesValue) . "";
            
        }
        echo "Total US Sales: " . $usTotal; 
        echo "";    
        
        echo "Sales by Province for Year " . $year . " for Canada:";
        foreach($caArr as $caState =&gt; $caSalesValue)       
        {
            echo $caState . ": " . wc_price($caSalesValue) . "";
            
        }
        echo "Total Canada Sales: " . $caTotal; 
        echo "";
    
        echo "Sales by State for Year " . $year . " for Mexico:";
        foreach($mxArr as $mxState =&gt; $mxSalesValue)       
        {
            echo $mxState . ": " . wc_price($mxSalesValue) . "";
            
        }
        echo "Total Mexico Sales: " . $mxTotal; 
        echo "";
    
    
    }
    
    1. Awesome! All your HTML chars have been decoded and show like “&gt” for example. If you want to send a revision, feel free to do so

      1. For anyone wanting to use this code, there are some HTML entity references that were triggering a fatal error on my site. Run a search and replace for [php]>[php] and change it to [php]>[php] and this snippet will work perfectly.

        1. Ok, my comment above got auto-corrected. The HTML entity you want to replace with “>” is “>”

  5. It works great for me for all years except 2019! I don’t fully understand why, I can parse data for 2018 and 2020 but not for 2019. I get the following error: “Fatal error: Allowed memory size of 805306368 bytes exhausted (tried to allocate 20480 bytes) in /home/dermapla/public_html/wp-includes/wp-db.php on line 1995”

    Just a heads up. I do appreciate the snippet though!

    I suppose I will try to find a different solution.

    1. I guess you have too many orders in 2019 and the snippet crashes. It is definitely possible to fix this in regard to performance, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  6. This code works but this is slower version. Doesn’t work with huge data. Better if this code written for Mysql Query.

    1. Ok thank you!

  7. Awesome. This helped beyond measure!

    Took some time to add all 50 states to the array but otherwise, was excellent. If you do ever build a plugin for this setup so that users could just install and enter the date range, I would pay for that! πŸ™‚

    1. Thank you!

      1. the following line generates an error now in the current WooCommerce Orders page:

        $reports['orders']['reports'] = array_merge($reports['orders']['reports'],$array);

        Error reads:

        Warning: array_merge(): Expected parameter 1 to be an array, null given in /home/kessler5/public_html/wp-content/themes/flatsome-child/functions.php on line 135

        Line 135 is where it sits in my child theme’s functions.php file of course. From what I can tell, it is not creating any issues anywhere else.

        1. Not sure if this is due to the fact WooCommerce discontinued their reports admin. If you find a fix let me know!

          1. I have the same issue. The extra report option causes the array_merge error and I have been unable to figure out how to correct this. Any ideas? Love the snippet otherwise!!

    2. Agreed Dave, I would absolutely pay for a plugin that did this.

  8. This is so helpful. Thank you! I have four states that I needed to pull information for, and this did the trick!

    How difficult would it be to display by month within the year totals? For instance, 2017 is already showing for the year – then filter down by month within the state totals like so:

    WA > Jan – $xxx; Feb – $xxx; Mar – $xxx | CA > Jan – $xxx; Feb – $xxx; Mar – $xxx and so on?

    1. Karen, thanks so much for your comment! Yes, this is totally possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  9. Hello, I am using Woocommerce Brand Plugin.

    Plugin Link: https://woocommerce.com/products/brands/

    I want to Get Sales by Brand Report. How can I do this ?

    Regards

    1. James, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  10. Cool Idea!

    What if i need to make this for Romania? Should i put RO to states?

    Because now it gives me an error.

    We put Romanian states using a plugin, but your snippet doesnt seem to work with that states https://prntscr.com/gnejer

    Can you direct me how to change? thanks

    1. Cristian, thanks for your comment! I believe I already helped you via Bloomer Armada support. Hope you managed to fix it πŸ™‚

  11. Works great! Thanks. How about a list of 10 states with most sales?

    1. Thank you πŸ™‚ Sure, that can be done, you will need to do some PHP edits πŸ™‚

  12. Every morning I wake-up I look forward to seeing your e-mail. Another awesome PHP snippet I’ve already added all the states and they work fabulously. Great work.

  13. Really nice excellent tutorial

Questions? Feedback? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between shortcodes: [php]code_here[/php]. Failure to complying with this (as well as going off topic, not writing in English, etc.) will result in comment deletion. 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 BloomerArmada to get blog comment reply priority, ask me 1-to-1 WooCommerce questions and enjoy many more perks. Thank you :)

Your email address will not be published.