Created
December 14, 2018 11:23
-
-
Save simonhughes/44e2ecdc70f287dc73c7634dc44f6e97 to your computer and use it in GitHub Desktop.
WordPress: add custom taxonomies to search query.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Filter: extend search query to look for custom taxonomies. | |
*/ | |
add_filter('posts_where', function ($where) { | |
global $wpdb; | |
if (is_search()) { | |
$where .= " OR (t.name LIKE '%".get_search_query() . "%' AND {$wpdb->posts}.post_status = 'publish') "; | |
} | |
return $where; | |
}); | |
/** | |
* Filter: add post_terms tables to search query. | |
*/ | |
add_filter('posts_join', function ($join) { | |
global $wpdb; | |
if (is_search()) { | |
$join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id | |
LEFT JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id | |
LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id"; | |
} | |
return $join; | |
}); | |
/** | |
* Filter: add 'group by' to query to prevent duplicate post results. | |
*/ | |
add_filter('posts_groupby', function ($groupby) { | |
global $wpdb; | |
$groupby_id = "{$wpdb->posts}.ID"; | |
if (!is_search() || strpos($groupby, $groupby_id) !== false){ | |
return $groupby; | |
} | |
if (!strlen(trim($groupby))){ | |
return $groupby_id; | |
} | |
return $groupby . ", " . $groupby_id; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment