Display Only Post Search Results on Your WordPress

If you like to display only post search results on your WordPress website, then here we have a simple solution to filter only post results on the search page. The WordPress search results are developed with default to get all the search results. To avoid unwanted results let us filter only the post results using a simple function.
Use the below code in your functions.php and you get only the post results on the search page.
1 2 3 4 5 6 7 |
function searchFilter($query) { if ($query->is_search) { $query->set('post_type', 'post'); } return $query; } add_filter('pre_get_posts','searchFilter'); |
In the above code, we set a simple search query function to filter the results. You also change the post type in your function if you are used Custom Post Type.
Display Post Search Results Based on Users
To customized post results based on users let us declare simple condition before the post search function. The below code will exclude post search result only for the admin.
1 2 3 4 5 6 7 8 9 |
if (!is_admin()) { function searchFilter($query) { if ($query->is_search) { $query->set('post_type', 'post'); } return $query; } add_filter('pre_get_posts','searchFilter'); } |
In the above code, we used the same function but with excluding admin using IF condition. You can change the user roles as per your requirement.
Conclusion:
I hope you enjoyed the article by displaying only post search results on your WordPress site. If you have any queries about this topic let me know in the comment section and if you loved this article share it with your friends.
Post SearchWithout Pluginwordpress
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]