0

I'm currently able to return woocommerce orders using the wc_get_orders() and WC order query.

https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query

My query for orders is:

$query = new WC_Order_Query( array(
   'paginate' => true,
   'limit' => 2,
   'orderby' => 'date',
   'order' => 'DESC',
) );

$activity = $query->get_orders();

Woocomerce docs link above shows you can query by custom meta.

/**
 * Handle a custom 'customvar' query var to get orders with the 'customvar' meta.
 * @param array $query - Args for WP_Query.
 * @param array $query_vars - Query vars from WC_Order_Query.
 * @return array modified $query
 */
function handle_custom_query_var( $query, $query_vars ) {
    if ( ! empty( $query_vars['customvar'] ) ) {
        $query['meta_query'][] = array(
            'key' => 'customvar',
            'value' => esc_attr( $query_vars['customvar'] ),
        );
    }

    return $query;
}
add_filter( 'woocommerce_order_data_store_cpt_get_orders_query', 'handle_custom_query_var', 10, 2 );

I can't work out how to query by product ID in order to show orders for a specific product and have working pagination.

Once the query has returned orders I am able to get the order product IDs using the get_items() function. But then I can't paginate from the original query correctly.

Is there another method for achieving this? would the using the woocomerce API be a better method or a direct SQL query?

Help would be appreciated.

  • You should better use a SQL query [to get orders by product ID](https://stackoverflow.com/a/43669138/3730754) as `WC_Order_Query` don't handle querying on any order item data. Your actual way is just very heavy as you query first all orders then you filter them using `get_items()`… – LoicTheAztec Jan 21 '18 at 18:45
  • Thanks Lioc - using an SQL query is definitely the best way to go. I've found this stack question that is what i'm looking for. https://stackoverflow.com/questions/43664819/get-all-orders-ids-from-a-product-id - I'm now trying to figure out how to paginate the wpdb query. Would be grateful for any help on this. –  Jan 23 '18 at 15:34

0 Answers0