Order search results

0.0/5
<?php
function my_pre_get_posts( $query ) {
	

	if( is_admin() ) { if the query is for an admin page, return
		return $query;
	}
	
	if (is_search()) { if the query is for a search, set orderby 
		$query->set('orderby', 'meta_value');	
		$query->set('meta_key', 'new_product');	 
	}

	return $query;

}


/*** sort by two  fields TODO

$args = array(
    'meta_query' => array(
        'relation' => 'AND',
        'query_one' => array(
            'key' => 'key_one',
            'value' => 'value_one', // Optional
        ),
        'query_two' => array(
            'key' => 'key_two',
            'compare' => 'EXISTS', // Optional
        ), 
    ),
    'orderby' => array( 
        'query_one' => 'ASC',
        'query_two' => 'DESC',
    ),
) );

***/

add_action('pre_get_posts', 'my_pre_get_posts');

Comments and reviews

{{ reviewsTotal }} Review
{{ reviewsTotal }} Reviews
{{ options.labels.newReviewButton }}
{{ userData.canReview.message }}

Description

This snippets is a query filter that sets the query orderby and meta_key if the query is for a search and isn’t for an admin page

Author

Tags

This snippet is untagged