Search code examples
wordpresswoocommercehook-woocommerce

Unable to add meta_query to woocommerce_product_query


I am trying to add my custom meta_query to WooCommerce main query using the woocommerce_product_query hook.

I tried this code:

function testing_woo_product_query( $q ){ 
    $args = array(
      'relation' => 'AND',
      array(
        'meta_key'  => '_price',
        'value'     => 10,
        'compare'   => '>=',
      ),
      array(
        'meta_key'  => '_price',
        'value'     => 30,
        'compare'   => '<=',
      )
    );
    
    $q->set( 'meta_query', $args ); 

}
add_action( 'woocommerce_product_query', 'testing_woo_product_query' );

But the code doesn't work. Can anybody tell me where is the problem?


Solution

  • Your Meta Query should use key and not meta_key - also you can use "between => array (low number, high number). You can see the proper format here WP Function Reference meta_query

    This will do what you are trying to do above:

    function testing_woo_product_query( $q ){ 
        $args = array(
          array(
            'key'       => '_price',
            'value'     => array( 10 , 30 ),
            'compare'   => 'BETWEEN',
            'type'      => 'numeric'  
          ),
        );
    
        $q->set( 'meta_query', $args );
    
    }
    add_action( 'woocommerce_product_query', 'testing_woo_product_query' );
    

    Be warned though, that this will effect shop and archive / category pages unless you qualify your function with specific details.