Bounties /Pin to ProfileBookmark

How to extend the WordPress Search to Taxonomies?

By default, WordPress Search is somewhat limited and seems to pull results based on Title/Content only. If I write a Post and Tag it “JavaScript” but don’t mention that specific keyword in the Title/Content, searching the site for JavaScript won’t show this Post in the search results despite the Tag.

What would be a minimal function to extend WP search to Tags, Categories, and Custom Taxonomies? Ideally, this could be done without the use of a plugin like WP Extended Search.

PHPWordPress
answer
@joshuaburlesoThere are a few ways to go about this in WP. In terms of ease and extensibility, you should be able to use, and go with, the pre_get_posts hook. How you implement custom taxonomies is going to depend on how you created them. If you used a plug-in then sometimes these have some funky naming conventions (or even on rare occasion have a tricky way of finding them), just check the docs for the plugin if that's the case; it's generally not difficult. In this case I'm going to pretend you have a single self-defined custom taxonomy called "stack". function expand_search($query) { if (!is_admin() && $query->is_search) { $query_term = $query->get('s'); if(!$query_term) return; $query_terms = explode(' ', $query_term); // optional // don't forget to sanitize, I'm not going to bother here array_push($query_terms, $query_term); $query->set( 'tax_query', array( 'relation' => 'OR', array( array( 'taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => $query_terms ), array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => $query_terms ), array( 'taxonomy' => 'stack', 'field' => 'slug', 'terms' => $query_terms ) ) ) ); } } add_action( 'pre_get_posts', 'expand_search' ); As a side-note, you could of course make your life easier and use a function to generate these very repeated query filter definitions. For example: function tax_query_filter($taxonomy, $terms, $field = 'slug') { return array( 'taxonomy' => $taxonomy, 'field' => $field, 'terms' => $terms ); } Like I said, this isn't the only way to go about it, but it's the strategy I used when I worked with WP and it worked well.
×

Success!

Help @buildinteractive spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with Github
about: ({
version: 0.1.6 BETA 11.29,
whats_new: article editor v2,
up_next: tip code demos,
coming_soon: embeddable tipping,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.6,
notes: article editor refresh

version: 0.1.5,
notes: added pins + new badge

version: 0.1.4,
notes: home refresh + tools

version: 0.1.3,
notes: added reference + demos
)...
recent_tips: (
tipper: @dert,
amount: 1000 SATS,
source: article

tipper: Anonymous,
amount: 1000 SATS,
source: article

tipper: @Loverboylove,
amount: 500 SATS,
source: article
)...