使用 SQL 查询按优惠券代码和日期范围获取 WooCommerce 订单

问题描述

我正在尝试按优惠券代码和日期获取订单数据。我已经添加了这个代码。但是如何通过优惠券代码和日期查找数据?

$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);

解决方法

以下自定义函数将使用自定义 SQL 查询按优惠券代码和日期范围获取 WooCommerce 处理和完成的订单 ID:

/*
 * Get WooCommerce orders Ids by coupon code and date range
 * 
 * @param string $coupon_code The coupon code
 * @param string $date_from The starting date (format 'Y-m-d')
 * @param string $date_to The end date (format 'Y-m-d')
 * @param array  $statuses The order statuses (optional | Default "processing" and "completed"
 *
**/
function get_order_ids_by_coupon_and_date_range( $coupon_code,$date_from,$date_to,$statuses = array() ){
    // Default order statuses set to 'processing' and 'completed'
    $statuses = empty($statuses) ? array('processing','completed') : $statuses;

    global $wpdb;

    return $wpdb->get_col( $wpdb->prepare("
        SELECT p.ID
        FROM $wpdb->posts p
        INNER JOIN {$wpdb->prefix}woocommerce_order_items oi
            ON p.ID = oi.order_id
        WHERE p.post_type = 'shop_order'
            AND p.post_status IN ('wc-" . implode("','wc-",$statuses )."')
            AND p.post_date BETWEEN '%s' AND '%s'
            AND oi.order_item_type = 'coupon'
            AND oi.order_item_name = '%s'
    ",sanitize_title( $coupon_code ) ) );
}

代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。

用法示例:

$coupon_code = 'special10';
$date_from   = '2021-02-01';
$date_to     = '2020-03-01';

$orders_ids  = get_order_ids_by_coupon_and_date_range( $coupon_code,$date_to );

echo '<pre>' . print_r( $orders_ids,true ) . '</pre>';

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...