获取Woocommerce当天订单的总购买金额

时间:2018-07-03 10:57:00

标签: php sql wordpress woocommerce orders

对于Woocommerce,我在下面编写了代码,试图获取今天的订单总购买量:

function order_total_woo_fahad(){

    // Get orders from people named John that were paid in the year 2016.
$orders = wc_get_orders( array(
    'date_paid' => '2018-07-03'
) );
$total_of_all=0;
for($i=0;$orders[i];$i++)
    $total_of_all= $orders[i]->get_total();
    return $total_of_all;
}

但是它返回null。

我做错了什么?如何获得当天的订单总购买金额?

2 个答案:

答案 0 :(得分:3)

获取此信息的最佳,有效方法是使用以下非常简单的SQL查询,该查询将获得“处理中”和“已完成”订单状态在过去24小时内所有订单总数的总和:

function get_daily_purchases_total(){
    global $wpdb;

    return $wpdb->get_var( "
        SELECT DISTINCT SUM(pm.meta_value)
        FROM {$wpdb->prefix}posts as p
        INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
        WHERE p.post_type LIKE 'shop_order'
        AND p.post_status IN ('wc-processing','wc-completed')
        AND UNIX_TIMESTAMP(p.post_date) >= (UNIX_TIMESTAMP(NOW()) - (86400))
        AND pm.meta_key LIKE '_order_total'
    " );
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。


用法示例-显示每日购买的格式化总金额:

<?php echo '<p>Total purchased of the day: ' . strip_tags( wc_price(get_daily_purchases_total() ) ) . '</p>'; ?>

如果您要改为基于“今天”日期总计,您将在代码中替换以下行:

AND UNIX_TIMESTAMP(p.post_date) >= (UNIX_TIMESTAMP(NOW()) - (86400))

通过此行:

AND DATE(p.post_date) >= CURDATE()

答案 1 :(得分:0)

<?php
global $wpdb;

$date_from = '2015-11-20';
$date_to = '2015-12-20';
$post_status = implode("','", array('wc-processing', 'wc-completed') );

$result = $wpdb->get_results( "SELECT * FROM $wpdb->posts 
            WHERE post_type = 'shop_order'
            AND post_status IN ('{$post_status}')
            AND post_date BETWEEN '{$date_from}  00:00:00' AND '{$date_to} 23:59:59'
        ");

echo "<pre>";
print_r($result);
?>