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' ); endwhile; wp_reset_postdata();