It has been a month since my last post. That is due to the fact that three weeks ago I became a father for the first time. I just have not had the time to sit down and gather my development thoughts. Things have settled down a bit and I decided to dig into the WordPress search query.
More specifically, I want the WordPress search to extend to category and post tag names, which comes down to searching on the taxonomy name. Lucky for me, WordPress has filters to extend the search query.
Send in the filters
Use posts_join filter to perform an INNER JOIN of the terms, term_relationship, and term_taxonomy tables on the posts table.
To include a clause to search the text being search, the posts_where filter is available to append an extra where clause.
The included taxonomy names can be narrowed down to category and post_tags. Wildcards are appended on both sides of the search criteria against the term name.
Finally, the posts_groupby filter is used to aggregate all the post IDs that will fall into out query to match the where clause.
The results may vary
You may not get what you expect. Categories and tags are usually single words. If a search contains more than one word, most categories and tags will be skipped.
This could be avoided by chunking the search words and creating a clause for each chunk against the query. This method could produce more overhead and probably not recommended for larger database.
It should also be noted that including a wild card search on category and tag names isn’t exactly appropriate in most cases. This would best be used with custom taxonomies such as actors for a movie database.
Feel free to checkout the Github version of this code as a plugin.