Menu Close

WooCommerce: Calculate Sales by State

default

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.

If you click on the brand new “Sales by State” submenu link, you will see this custom admin page with the total amount for each state as defined inside the snippet below

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
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

// -----------------------
// 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>';
 
}
View Source
Posted in WooCommerce Tips