Skip to content

Instantly share code, notes, and snippets.

@claus
Created August 17, 2018 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save claus/54ce760001fb02131c07b47b2b8db9e2 to your computer and use it in GitHub Desktop.
Save claus/54ce760001fb02131c07b47b2b8db9e2 to your computer and use it in GitHub Desktop.
Wordpress: Also search tags in addition to post title and content
function tax_search_join( $join, $query ) {
global $wpdb;
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$join .= "
INNER JOIN
{$wpdb->term_relationships} ON {$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id
INNER JOIN
{$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_taxonomy_id = {$wpdb->term_relationships}.term_taxonomy_id
INNER JOIN
{$wpdb->terms} ON {$wpdb->terms}.term_id = {$wpdb->term_taxonomy}.term_id
";
}
return $join;
}
function tax_search_where( $where, $query ) {
global $wpdb;
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$where .= $wpdb->prepare( " OR (
{$wpdb->term_taxonomy}.taxonomy LIKE 'post_tag'
AND
{$wpdb->terms}.name LIKE ('%%%s%%')
) ", get_query_var('s'));
}
return $where;
}
function tax_search_groupby( $groupby, $query ) {
global $wpdb;
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$groupby = "{$wpdb->posts}.ID";
}
return $groupby;
}
add_filter('posts_join', 'tax_search_join', 10, 2);
add_filter('posts_where', 'tax_search_where', 10, 2);
add_filter('posts_groupby', 'tax_search_groupby', 10, 2);
@claus
Copy link
Author

claus commented Aug 17, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment