I am trying to include categories in search results. I’ve been searching for hours now with no solution.
By “including categories” I don’t mean search in a certain category, I mean let’s say I have a bicycle store and have many companies included in the site; a user searched for BMX mountain cross
for example. It will return the category BMX first (by clicking you’ll be sent to the category page) and the posts related to the search term like WordPress normally does.
Does anyone have any clues or could point me to the right direction?
I’m using this code in my search.php above the main loop:
This code does an extra DB query, but search for categories not only associated to returned posts, but does an extra seach for each word in a search term and brings all found categories – even empty.
Use
get_terms()
, then you don’t need to use a custom query to the database.Based on birgire‘s answer on a similar question: https://wordpress.stackexchange.com/a/239680/50432
I’ve created a custom search results page that matches the keyword (s) with categories, posts, cpt’s…
Here’s sthe code for the categories (it also shows a category ACF field for images:
Obviously possible, if it works like this, I’m using TwentyTwelve, you have to edit
search.php
. You will find the loop there:So, the loop is taking the
post_format()
. So you have to editcontent.php
. Here you will find these:Just change that to:
If everything goes right, than it will echo the Category associated the search result. But if everything goes right like we want. 🙂
Based on the @PhilOwen answer, I added the following to the top of my theme’s search.php page:
I think it will often make sense to display the taxonomy term matches–if they exist–above the specific items, as they would be higher up in the hierarchy of data.
I found a better way and wanted to share
no need that use $wpdb
this code work for me:
this code search in product category and It does not need to be exactly the same
PROBLEM: As of march 2022, wordpress doesn’t search for category or tag.
SOLUTION/WORKAROUND: Use a plugin to allow searching for category or tag. I’ve tested it with the free version of the Relevanssi-Plugin. https://www.relevanssi.com/features/. Other Plugins may work, too.
DISCLAIMER: I am not affiliated with relevanssi or any other wp search plugin vendor.