Skip to content

Instantly share code, notes, and snippets.

@ewistrand
Created February 25, 2016 13:21
Show Gist options
  • Save ewistrand/f0960d0df77c21be0c33 to your computer and use it in GitHub Desktop.
Save ewistrand/f0960d0df77c21be0c33 to your computer and use it in GitHub Desktop.
Add tags to wordpress search
<?php
// ADD Tags To SEARCH
function my_smart_search( $search, &$wp_query ) {
global $wpdb;
if ( empty( $search ))
return $search;
$terms = $wp_query->query_vars[ 's' ];
$exploded = explode( ' ', $terms );
if( $exploded === FALSE || count( $exploded ) == 0 )
$exploded = array( 0 => $terms );
$search = '';
foreach( $exploded as $tag ) {
$search .= " AND (
($wpdb->posts.post_title LIKE '%$tag%')
OR ($wpdb->posts.post_content LIKE '%$tag%')
OR EXISTS
(
SELECT * FROM $wpdb->comments
WHERE comment_post_ID = $wpdb->posts.ID
AND comment_content LIKE '%$tag%'
)
OR EXISTS
(
SELECT * FROM $wpdb->terms
INNER JOIN $wpdb->term_taxonomy
ON $wpdb->term_taxonomy.term_id = $wpdb->terms.term_id
INNER JOIN $wpdb->term_relationships
ON $wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id
WHERE taxonomy = 'post_tag'
AND object_id = $wpdb->posts.ID
AND $wpdb->terms.name LIKE '%$tag%'
)
)";
}
return $search;
}
add_filter( 'posts_search', 'my_smart_search', 500, 2 );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment