Home » WooCommerce: Calculate Sales by State

WooCommerce: Calculate Sales by State

by Tutor Aspire

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 tutoraspire.com FREE
 * @sourcecode    https://tutoraspire.com/?p=72853
 * @author        Tutor Aspire
 * @testedwith    WooCommerce 3.1.2
 */

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

add_filter( 'woocommerce_admin_reports', 'tutoraspire_admin_add_report_orders_tab' );

function tutoraspire_admin_add_report_orders_tab( $reports ) { 

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

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

return $reports; 
}

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

function tutoraspire_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 "

Sales by State for Year " . $year . "

"; echo "CA: " . wc_price($total_ca) . ""; echo "WA: " . wc_price($total_wa) . ""; }

You may also like