Skip to content

Instantly share code, notes, and snippets.

@jackgregory
Created December 21, 2017 13:08
Show Gist options
  • Save jackgregory/c755dca1fab86eaaf76e64af0bbe0af6 to your computer and use it in GitHub Desktop.
Save jackgregory/c755dca1fab86eaaf76e64af0bbe0af6 to your computer and use it in GitHub Desktop.
Match exact search term including tax/terms
add_filter( 'posts_search', 'my_search_is_perfect', 20, 2 );
function my_search_is_perfect( $search, $wp_query ) {
global $wpdb;
if ( empty( $search ) )
return $search;
$q = $wp_query->query_vars;
$n = !empty( $q['exact'] ) ? '' : '%';
$search = '';
$searchand = '';
foreach ( (array) $q['search_terms'] as $term ) {
$term = esc_sql( like_escape( $term ) );
$search .= "{$searchand}(
$wpdb->posts.post_title REGEXP '[[::]]')
OR ($wpdb->posts.post_content REGEXP '[[::]]')
OR ((SELECT COUNT(wp_terms.term_id) FROM wp_term_relationships
LEFT JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
LEFT JOIN wp_terms ON wp_term_taxonomy.term_id = wp_terms.term_id
WHERE (wp_term_relationships.object_id = $wpdb->posts.ID)
AND (wp_terms.name REGEXP '[[::]]')) > 0)
";
$searchand = ' AND ';
}
if ( ! empty( $search ) ) {
$search = " AND ({$search}) ";
if ( ! is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password = '') ";
}
return $search;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment