I have sorted my WooCommerce product list (Training events) with a pre_get_posts Filter (as shown below), to sort by Date via custom field "startdate2". This works fine for the WooCommerce product list, but does not affect the sorting of a search result list, displayed via the same template (archive-product.php).

The product posts in search result are always in wrong order. I tried out a lot but nothing works and I can't figure out why. Can it be that the pre_get_post filter does NOT work for search results? Or is it probably necessary to write a second pre_get_post filter only for the search result list?

I also tried out an extra query in the template only for "is_search()" - but does not work too.

// Sort Products by startdate2
function my_pre_get_posts( $query ) {
    // do not modify queries in the admin
    if ( is_admin() ) {
        return $query;

    // only modify queries for 'product' post type
    if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'product' ) {

        $query->set('orderby', 'meta_value');
        $query->set('meta_type', 'DATE');
        $query->set('meta_key', 'startdate2');
        $query->set('order', 'ASC');

    // return
    return $query;
add_action('pre_get_posts', 'my_pre_get_posts');

// alternative: Extra query in template:
$args = array(
    'post_type'   => 'product',
    'orderby' => 'meta_value_num',
    'meta_key'=> 'startdate2',
    'order'   => 'ASC'

// the query
$the_query = new WP_Query( $args ); 

if ( $the_query->have_posts() ) : 

    while ( $the_query->have_posts() ) : $the_query->the_post(); 
         wc_get_template_part( 'content', 'product' ); 


1 Answer 1


If searching via Wordpress ?s=keyword (not WooComm's Product Search), post_type isn't set or used, so the following would return false:

if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'product' ) {

You can explore what $query->query_vars contains on your Products page vs your Products Search page by just printing it and killing the page:

function my_pre_get_posts( $query ) {
  echo "<pre>".print_r($query->query_vars,true)."</pre>";

If you are using WooComm's search (and the query is like ?s=keyword&post_type=product) and WooComm does have post_type set, try firing your action with a later priority:

add_action('pre_get_posts', 'my_pre_get_posts',999);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.