0

Im trying to get all orders that have a certain value in a custom meta data.

Here is a basic query using wc_get_orders

$delivered_orders = (array) wc_get_orders( array(
        'limit'        => -1,
        'status'       => 'wc-delivered',
        'type' => 'shop_order',
        'date_created' => '>'. $from,
    ) );

Here im getting all orders that have the status wc-delivered and that were created from a certain date, I also need to filter those which their meta data _my_meta_data is equal to "some value"

svelandiag
  • 4,231
  • 1
  • 36
  • 72

2 Answers2

1

You can add Custom Parameter to query variables, like this:

1. Filter the generated query.

/**
 * 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 );

2. Usage

$orders = wc_get_orders( array( 'customvar' => 'somevalue' ) );
Andy Nguyen
  • 131
  • 1
  • 9
-2
/**
* you can try this below code 
*/
    
$args = array(
    'status' => array('wc-delivered'),
);
$orders = wc_get_orders( $args );
wpdevloper_j
  • 330
  • 2
  • 12