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>";

}

Share:

Leave a Reply