Extend the default WordPress Search


Just a short snippet I have written for one of my WordPress-based web site.
By default, the WordPress search only checks post titles and post contents. What I wanted to do was to also search post tags and post comments.

I first tried to use an existing plugin, like Search Everything. But it was searching for sentences. As an example, if I searched for “Eclipse Menu”, it was searching the exact expression. And not all the posts that contain both key words “Eclipse” and “Menu”.

I spent a lot of time to search an existing solution.
I finally created my own one. You can add the following code in the functions.php file of your theme.

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 (
			(wp_posts.post_title LIKE '%$tag%')
			OR (wp_posts.post_content LIKE '%$tag%')
				SELECT * FROM wp_comments
				WHERE comment_post_ID = wp_posts.ID
					AND comment_content LIKE '%$tag%'
				SELECT * FROM wp_terms
				INNER JOIN wp_term_taxonomy
					ON wp_term_taxonomy.term_id = wp_terms.term_id
				INNER JOIN wp_term_relationships
					ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
				WHERE taxonomy = 'post_tag'
					AND object_id = wp_posts.ID
					AND wp_terms.name LIKE '%$tag%'

    return $search;

add_filter( 'posts_search', 'my_smart_search', 500, 2 );

With this function, you customize the search.
When there are several key words, you search for posts which contain both of them, no matter if they are in the post title, content, tags or comments.

About this entry