If you are using more than one Category in your posts of your WordPress-based project, and you want your search feature to work for only one of them, this method is for you.
First of all, it is useful to remind you: For simple operations you can do without using a plugin, please do not install plugins on your site! There are 2 main reasons for this:
Security: Plugins are at the discretion of the person who wrote that one. Even if there is no security vulnerability at the time you install it, one may appear in the code of that add-on at a later date and you will not even be aware of it.
Speed: Plugins consume resources. In addition, since each of them carries out several separate processes, it will have negative effects on the opening speed of your page.
So, what are we going to do?
If you know what you’re doing, interfere with your site’s codes by yourself . In our example here, we will solve our problem by adding a simple function to the functions.php
file of WordPress.
Case Study: Marinalar.com
While preparing Marinalar.com for publication, we had a problem with searching. We had 2 types of content defined as “posts”: News and Marinas. But our user experience research revealed that the search feature doesn’t necessarily cover the news, and is often distracting. So the search result should have listed only Marinas.
At the end of our research, we discovered that we could solve this problem from the code, not from the frontend.
Let me tell you how you can easily handle this process in 2 steps.
In Which Category the search will be done?
The first thing we need to know is to learn the ID of the category you want to search. For this, we enter the Posts
> Categories
option from the left menu of your wordpress site.
Then, we move the mouse over the category whose ID we want to learn and look for the tag_ID=
part in the link address. You can find this out by right-clicking on the link and choosing “inspect element” or by looking at what the link address.
In our example it says tag_ID=63
. In other words, the ID of the Marinas category on our WordPress site is 63. We will also use this number in our code.
It’s time to write our code
We write a new function in functions.php
:
// SEARCH IN SINGLE CATEGORY
function single_category_search( $query ) {
if ( is_admin() || ! $query->is_main_query() )
return;
if ( $query->is_search ) {
$query->set( 'cat', '63' ); // Search within this ID
}
}
add_action( 'pre_get_posts', 'single_category_search', 1 );
That is all.
Now, all the searches you will make on your WordPress site will be in the category you specify and the results will only be presented within this set.
For detailed information about the pre_get_posts
we use here: developer.wordpress.org/reference/hooks/pre_get_posts/
Top comments (0)