【问题标题】:How to get WooCommerce orders total sales without taxes?如何获得无税 WooCommerce 订单的总销售额?
【发布时间】:2021-04-25 01:15:19
【问题描述】:

所以我想计算我的网站的总销售额(不含税)。但是,我在网站上有大量订单。使其崩溃页面,因为它无法处理计算。有没有更好的方法来从 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;

}

【问题讨论】:

  • 你检查过报告部分吗?

标签: php sql wordpress woocommerce orders


【解决方案1】:

您可以使用这个自定义函数,该函数使用非常轻量级的 SQL 查询,使用 WordPress WPDB Class 来获取订单总销售额(不含税)。

它将从具有“已完成”、“处理中”、“暂停”和“待定”状态的订单中获取总销售额。

主要功能代码:

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')
    ");
}

然后你可以在你自己的函数中使用它,比如:

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

代码位于活动子主题(或活动主题)的functions.php 文件中。在 WooCommerce 4+ 中测试并运行。


该函数还允许获取:

  • 订单总销售额(含税)get_orders_total_sales('including')
  • 订单总销售额(仅税)get_orders_total_sales('taxes')
  • 订单总销售额(仅限运费)get_orders_total_sales('shipping')

【讨论】:

    猜你喜欢
    • 2016-02-18
    • 2022-10-04
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多