Laravel Expert

WpEasyTuts » Tutorials

How to Create Custom Search Results in WordPress

Posted on October 10, 2017 by

how  create custom search results wordpress

Limit Search Results for Specific Post

Would you like to limit your search result for specific post type in WordPress? For example if your blog have 3 different post types such as News, Videos and Downloads and you would like to display only News in search result then add the following code in the end of functions.php file inside your theme folder.

function easytuts_search($query) {
    if ($query->is_search && !is_admin()) {
        $query->set('post_type','news');
    } 
	return $query;
}
add_filter('pre_get_posts','easytuts_search');

If you would like to add multiple post type to display in search results then just add post types in a array.

$query->set('post_type',array('news','videos'));

Search Result order by Comments and Custom Fields

Would you like to display posts with highest comments first or post with custom fields first? For example if you want to display first few search result with highest comments or you want to display first few results which have the highest custom field value or order by custom fields value? Add the following code in the end of functions.php file inside your theme folder.

function easytuts_search($query) {
    if ($query->is_search && !is_admin()) {
        $query->set('orderby','comment_count');
		$query->set('order','DESC');
    } 
	return $query;
}
add_filter('pre_get_posts','easytuts_search');

Add below code if you would like to display search result order by custom fields.

function easytuts_search($query) {
    if ($query->is_search && !is_admin()) {
        $query->set('meta_key','rating');
		$query->set('orderby','meta_value');
		$query->set('order','DESC');
    } 
	return $query;
}
add_filter('pre_get_posts','easytuts_search');

Above code will display first few results for posts which have highest value for custom field “Rating”. You can replace “meta_key” with your own custom field value.

Custom Search Results Example

Suppose Our website have post type movies and also simple post for blog. We also have one custom field called “movie rating” for movies. We would like to display only one post type in search result with highest rating posts first.

function easytuts_search($query) {
    if ($query->is_search && !is_admin()) {
        $query->set('post_type','movies');
		$query->set('meta_key','movie_rating');
		$query->set('orderby','meta_value');
		$query->set('order','DESC');
    } 
	return $query;
}
add_filter('pre_get_posts','easytuts_search');

No Comments

Leave a Reply