Jorge Rey
Jorge Rey

Reputation: 23

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

Hi I want to make a custom order query inside the WooCommerce template "orders.php" of My Account template.

The template that you edit "my-theme/woocommerce/templates/myaccount/orders.php"

The query is as follows. But I do not work with 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'))
    ),
  ),
) );

What may be wrong?

Thanks

Upvotes: 1

Views: 1202

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253978

First you should Overriding WooCommerce Templates via your Theme, but not directly in the plugin

Then, the main problem in this query comes from the post_status regarding WooCommerce orders, that is very specific.

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

So your working tested code should be now:

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

Or you can also use instead dedicated WooCommerce orders function wc_get_orders() which will give you all WC_Order objects instead of WP_Post objects, this way:

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

Then you will be able to use directly all WC_Order methods]2 on each $order object…

Upvotes: 2

Related Questions