在模板 myaccount/orders.php 中的 WooCommerce 3 中进行自定义查询

Make a custom query in WooCommerce 3 within the template myaccount/orders.php

您好,我想在我的帐户模板的 WooCommerce 模板 "orders.php" 中进行自定义订单查询。

您编辑的模板"my-theme/woocommerce/templates/myaccount/orders.php"

查询如下。但我不使用 Woocommerce 3。0.x

$customer_orders = get_posts( array( 
    'numberposts' => $order_count,
    'meta_key'    => '_customer_user',
    'meta_value'  => get_current_user_id(),
    'post_type'   => 'shop_order',
    'post_status' => 'publish',
    'date_query' => array(
    array(
      'after' => date('Y-m-d', strtotime($from)),
      'before' => date('Y-m-d', strtotime($to. ' + 1 days'))
    ),
  ),
) );

可能出了什么问题?

谢谢

首先你应该Overriding WooCommerce Templates via your Theme,但不要直接在插件中

然后,此查询中的主要问题来自 post_status 关于 WooCommerce 订单,非常具体。

## DEFINING VARIABLES, JUST FOR TESTING ##
    $order_count = -1; 
    $from = '2016/04/08';
    $to   = '2017/02/02';

所以你的工作测试代码现在应该是:

$customer_orders = get_posts( array(
    'numberposts' => -1,
    'meta_key'    => '_customer_user',
    'meta_value'  => get_current_user_id(),
    'post_type'   => 'shop_order',
    # HERE below set your desired Order statusses
    'post_status' => array( 'wc-pending', 'wc-processing', 'wc-on-hold', 'wc-completed' ),
    'date_query' => array( array(
        'after' => date( 'Y-m-d', strtotime( $from ) ),
        'before' => date( 'Y-m-d', strtotime( $to . ' + 1 days' ) ),
        'inclusive' => true, // If you want a before date to be inclusive,
    ) ),
) );

或者您也可以使用专用的 WooCommerce 订单功能 wc_get_orders(),这将为您提供所有 WC_Order对象而不是 WP_Post 个对象,这样:

$customer_orders = wc_get_orders( array(
    'numberposts' => -1,
    'meta_key'    => '_customer_user',
    'meta_value'  => get_current_user_id(),
    ## NOT NEEDED ## 'post_type'   => 'shop_order',
    'post_status' => array( 'wc-pending', 'wc-processing', 'wc-on-hold', 'wc-completed' ),
    'date_query' => array( array(
        'after' => date( 'Y-m-d', strtotime( $from ) ),
        'before' => date( 'Y-m-d', strtotime( $to . ' + 1 days' ) ),
        'inclusive' => true, // If you want a before date to be inclusive,
    ) ),
) );

然后你就可以在每个$order对象上直接使用所有WC_Order方法]2