skip to Main Content

I’ve used the ‘woocommerce_order_data_store_cpt_get_orders_query’ hook to add some custom meta query vars to the WC_Order_Query function. However the added keys seem to be ignored by the query.

I’ve used the following snippet for testing purposes;

add_filter( 'woocommerce_order_data_store_cpt_get_orders_query', 'custom_order_query', 10, 2 );
function custom_order_query($query, $query_vars){
    
    if ( ! empty( $query_vars['zone_id'] ) ) {
    
        $query['meta_query'][] = array(
            'key' => '_wcgd_delivery_region',
            'value' => esc_attr( $query_vars['zone_id'] ),
            'compare' => '='
        );
    }
    return $query;
}

Now, when using the WC_Order_query I expect to only get orders in the given zone_id. But this is not the case.

When I request a list of orders using

`
$vars = array(
        'customer_id' => 2526,
        'limit' => '5',
        'status'         => 'processing',
        'zone_id'  => 4,
        'return'            => 'ids'
        );


$query = new WC_Order_Query( $vars );
print_r($query->get_orders());`
`

I get all orders for the given customer_id, not the orders for the given customer_id/zone_id.

What am I doing wrong here? I’m pulling my hair out… I’ve just followed the WooCommerce docs, but I really can’t figure out why this is not working.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for pointing me in the right direction! Since I need to query multiple meta keys I ended up using this as a working solution;

        $args = array(
            'limit' => 1,
            'status' => 'processing',
            'return' => 'ids',
            'meta_query' => array(
                array(
                    'key' => $wcgd->region_meta,
                    'value' => $zone_id,
                    'compare' => '=',
                ),
                array(
                    'key' => $wcgd->substate_meta,
                    'value' => array('afhaal', 'parcelpro_dhl', 'parcelpro_postnl'),
                    'compare' => 'NOT IN'
                )
            ),
        );
    
        $query = new WC_Order_Query( $args );
        $query_orders = $query->get_orders();
    

  2. You can directly query custom metadata in your query using the following:

    $orders_ids = wc_get_orders( array(
        'status'        => 'processing',
        'limit'         => 5,
        'customer_id'   => 2526,
        'meta_key'      => '_wcgd_delivery_region',
        'meta_value'    => 4,
        'meta_compare'  => '=',
        'return'        => 'ids'
    ) );
    
    echo '<pre>'. print_r( $orders_ids, true ) . '</pre>';
    

    Tested and works.

    Related: Extend wc_get_orders() with a custom meta key and meta value

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search