WooCommerce函数全部失效,统计昨日订单的cron任务输出值全为0
问题原因与修复方案
核心问题点
- 错误调用订单查询方法:
Wc()->wc_get_orders()写法错误,wc_get_orders是WooCommerce原生全局函数,不需要通过WC()实例调用,该错误会直接导致订单查询失败,返回空结果 - 订单日期查询参数格式错误:WooCommerce的
date_created查询参数需传入时间范围数组,仅传入单个日期字符串无法匹配到昨日全天的订单 - 缺少WooCommerce依赖加载判断:部分场景下加载
wp-load.php后不会自动初始化WooCommerce,需要额外判断加载 - 手续费读取写法错误:
$order->get_fees()返回的是WC_Order_Item_Fee对象数组,不是关联数组,用数组下标读取会返回空值,导致小费统计始终为0 - 未取消订单查询分页限制:默认订单查询有分页上限,未指定无限制查询会导致仅返回前10条甚至更少的订单,统计值不全
修正后完整代码
<?php define('WP_USE_THEMES', false); require( dirname( __FILE__ ) . '/wp-load.php' ); // 判断WooCommerce是否加载,缺失则手动加载 if ( ! function_exists( 'wc_get_orders' ) ) { if ( file_exists( WP_PLUGIN_DIR . '/woocommerce/woocommerce.php' ) ) { require_once WP_PLUGIN_DIR . '/woocommerce/woocommerce.php'; } else { wp_die('WooCommerce 插件未安装'); } } // 定义昨日时间范围:00:00:00 到 23:59:59 $start_date = strtotime( 'yesterday 00:00:00' ); $end_date = strtotime( 'yesterday 23:59:59' ); // 正确的订单查询参数 $args = array( 'date_created' => array( 'after' => date( 'Y-m-d H:i:s', $start_date ), 'before' => date( 'Y-m-d H:i:s', $end_date ), ), 'limit' => -1, // 查询所有符合条件的订单,避免分页限制 'post_status' => array( 'wc-completed', 'wc-processing' ), // 可按需调整需要统计的订单状态 ); // 正确调用订单查询方法 $orders = wc_get_orders( $args ); // 初始化统计变量 $subtotal = 0; $gratuity = 0; $taxes = 0; if ( ! empty ( $orders ) ) { foreach ( $orders as $order ) { $subtotal += $order->get_subtotal(); // 统计小费 foreach ( $order->get_fees() as $fee ) { $gratuity += $fee->get_total(); } $taxes += $order->get_total_tax(); } } // 发送邮件 $to = 'jesse@munerismedia.com'; $subject = '昨日订单统计汇总'; $body = '<p>订单小计:' . $subtotal . '</p><p>小费总额:' . $gratuity . '</p><p>税费总额:' . $taxes . '</p>'; $headers = array( 'Content-Type: text/html; charset=UTF-8' ); wp_mail( $to, $subject, $body, $headers ); ?>
内容的提问来源于stack exchange,提问作者GGNoEffort
相关产品推荐
相关产品推荐

