skip to Main Content

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"

2

Answers


  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' ) );
    
    Login or Signup to reply.
  2. /**
    * you can try this below code 
    */
        
    $args = array(
        'status' => array('wc-delivered'),
    );
    $orders = wc_get_orders( $args );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search