0
votes

So i want to calculate the total sale amount, excluding tax, for my website. However, i have a enormous load of orders on the website. Making it crash the page because it can't handle the calculation. Is there a better way to calculate / retrieve this from WooCommerce?

function calculateTotalSales(){

    $orders = get_posts( array(
        'numberposts' => - 1,
        'post_type'   => array( 'shop_order' ),
        'post_status' => array( 'wc-completed', 'wc-processing', 'wc-pending' )
    ) );

    $total = 0;
    foreach ( $orders as $customer_order ) {
        $order = wc_get_order( $customer_order );
        $total += $order->get_total() - $order->get_total_tax();
    }
    
    update_option('totalSales', $totalSales);
    return $totalSales;

}
1
Have you checked the report section?mujuonly

1 Answers

1
votes

You can use this custom function that uses a very lightweight SQL query using WordPress WPDB Class to get orders total sales (excluding taxes).

It will get total sales from orders with "completed", "processing", "on-hold" and "pending" status.

The main function code:

function get_orders_total_sales( $type = 'excluding' ) {
    global $wpdb;

    // Excluding taxes (by default)
    if ( 'excluding' === $type ) {
        $column = 'net_total';
    }
    // Including taxes
    elseif ( 'including' === $type ) {
        $column = 'total_sales';
    }
    // only taxes
    elseif ( 'taxes' === $type ) {
        $column = 'tax_total';
    }
    // only shipping
    elseif ( 'shipping' === $type ) {
        $column = 'shipping_total';
    }

    return (float) $wpdb->get_var("
        SELECT SUM($column)
        FROM {$wpdb->prefix}wc_order_stats
        WHERE status IN ('wc-completed','wc-processing','wc-on-hold','wc-pending')
    ");
}

Then you can use it in your own function like:

function calculateTotalSales(){
    total_sales = get_orders_total_sales(); // get orders total sales (excluding taxes)
    update_option( 'totalSales', total_sales ); // Save it as a setting option
    return total_sales; 
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works in WooCommerce 4+.


The function also allow to get:

  • orders total sales (including taxes): get_orders_total_sales('including')
  • orders total sales (only taxes): get_orders_total_sales('taxes')
  • orders total sales (only shipping): get_orders_total_sales('shipping')