You’re filing your tax returns and need to know how much you earned in each state… but then find out WooCommerce doesn’t give you this calculation by default within its reports!
Don’t worry – today I’ll share a quick snippet so that you can calculate the amount you need in a second. Feel free to change the year, the country and the states in the snippet.
PHP Snippet: Generate Sales by State Report @ Custom WooCommerce Admin Subpage
/**
* @snippet Get Sales by State @ WooCommerce Admin
* @how-to Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @testedwith WooCommerce 8
* @community https://businessbloomer.com/club/
*/
// -----------------------
// 1. Create "Sales by State" submenu page
add_action( 'admin_menu', 'bbloomer_wp_dashboard_woocommerce_subpage', 9999 );
function bbloomer_wp_dashboard_woocommerce_subpage() {
add_submenu_page( 'woocommerce', 'Sales by State', 'Sales by State', 'manage_woocommerce', 'bb_sales_by_state', 'bbloomer_yearly_sales_by_state', 9999 );
}
// -----------------------
// 2. Calculate sales for all states
function bbloomer_yearly_sales_by_state() {
$year = 2023;
$sales_by_state = array();
echo "<h3>Sales by State For Year {$year} ($)</h3>";
$args = array(
'billing_country' => 'US', // COUNTRY
'status' => array( 'wc-completed' ),
'type' => 'shop_order',
'limit' => -1,
'return' => 'ids',
'date_created' => strtotime( "first day of january " . $year ) . '...' . strtotime( "last day of december " . $year ),
);
$orders = wc_get_orders( $args );
foreach ( $orders as $order_id ) {
$order = wc_get_order( $order_id );
$sales_by_state[$order->get_billing_state()] = isset( $sales_by_state[$order->get_billing_state()] ) ? $sales_by_state[$order->get_billing_state()] + $order->get_total() : $order->get_total();
}
echo '<pre style="font-size: 16px">';
ksort( $sales_by_state );
print_r( $sales_by_state );
echo '</pre>';
}
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: Add Second Description @ Product Category Pages In terms of SEO, if you’re trying to rank your product category pages, you really need to make the most of the default WooCommerce product category “description” and “thumbnail”. Most themes, if compatible with WooCommerce, will show this content right below the product category name and above products. Nothing new so far. But what if […]
WooCommerce: Add Column to Orders Table @ WP Dashboard The WooCommerce Orders Table, which can be found under WP Dashboard > WooCommerce > Orders, provides us with 7 default columns: Order – Date – Status – Billing – Ship to – Total – Actions. This is used by shop managers to have an overview of all orders, before eventually clicking on a specific one. […]
WooCommerce: Hide/Show The WP Admin Bar In previous WooCommerce versions, new customers could access the WP Admin black bar after purchase. Now this seems fixed. Still, what about other user roles, and what if you want to override this default behavior? Well, here’s a quick snippet for you – feel free to use it in your own WooCommerce site. Enjoy!
WooCommerce: Display Custom Filters @ WP Dashboard > Products If you go to WordPress Dashboard > Products you will find default product admin filters such as “Select a category”, “Filter by product type”, “Filter by stock status”. What if you want to add more custom filters to let your shop managers find products easily? For example, you could add “Filter by product tag” (“product […]
WooCommerce: Access Thank You Page from Order Admin I’ve been testing for over an hour but finally I found a way to make this work. When you are in “Edit Order” view under WordPress Dashboard > WooCommerce > Orders, there is a dropdown of “Order actions”: “Email invoice“, “Resend new order notification“, etc. A major problem I’ve always had while troubleshooting or working […]
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
37 thoughts on “WooCommerce: Calculate Sales by State”
Stacie M
Hello. Does this code snippet still work now that WooCommerce has done away with the Reports section and now uses the Analytics section? Thanks!
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.
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!
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' => '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:";
foreach($usArr as $usState => $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 => $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 => $mxSalesValue)
{
echo $mxState . ": " . wc_price($mxSalesValue) . "";
}
echo "Total Mexico Sales: " . $mxTotal;
echo "";
}
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.
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.
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!
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! ๐
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.
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!!
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?
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
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
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.
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!
Hello. Does this code snippet still work now that WooCommerce has done away with the Reports section and now uses the Analytics section? Thanks!
Works for me – I have WooCommerce Analytics disabled lol!
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.
Thanks for your feedback! I’ve revised the sign-up process, try again and let me know
Is it possible to add Sales by State as the first tab? Before Sales by date?
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!
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.
Nice!
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:
Awesome! All your HTML chars have been decoded and show like “>” for example. If you want to send a revision, feel free to do so
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.
Ok, my comment above got auto-corrected. The HTML entity you want to replace with “>” is “>”
Thank you. Also https://www.businessbloomer.com/woocommerce-calculate-sales-state/#comment-348485
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.
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!
This code works but this is slower version. Doesn’t work with huge data. Better if this code written for Mysql Query.
Ok thank you!
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! ๐
Thank you!
the following line generates an error now in the current WooCommerce Orders page:
Error reads:
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.
Not sure if this is due to the fact WooCommerce discontinued their reports admin. If you find a fix let me know!
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!!
Finally found a fix. Replace this
with this:
Thanks!
Agreed Dave, I would absolutely pay for a plugin that did this.
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?
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
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
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
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
Cristian, thanks for your comment! I believe I already helped you via Business Bloomer Club support. Hope you managed to fix it ๐
Works great! Thanks. How about a list of 10 states with most sales?
Thank you ๐ Sure, that can be done, you will need to do some PHP edits ๐
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.
Awesome!!!
Really nice excellent tutorial
Thank you ๐