Making WordPress Search Better

In this post I’m addressing a shortcoming of WordPress’ built in search function.

If you create a page or post using characters which are deemed “Special” such as <, >, &, etc. they are automatically stored as their html coded equivalents, &lt;, &gt;, &amp;, etc. This makes sure that the text is properly encoded for browsers to display.

Makes sense so far, right?

Well, the snag is that if you want to SEARCH for this text, it won’t work. A post containing “This & That” is stored as This &amp; That but when you type “This & That” in the search box, it retains the “&” and does NOT transform it to &amp; and the search comes up empty.

The following fixes that.  Open your theme’s “functions.php” and paste in the following code.

function searchfilter($query) {

    if ($query-&gt;is_search) { //Are we here because of a search?
        $zoe = htmlentities($query-&gt;get('s')); //Sanitize search text
        $query-&gt;set('s', $zoe) ; //Change search text (keyword) to cleaned version
    }

    return $query;
}

add_filter('pre_get_posts','searchfilter');

Additionally, if you want to add searching both Pages AND Posts, and not just Posts, add this line

$query-&gt;set('post_type',array('post','page')); //search BOTH pages AND posts...

The resulting code should look like this

function searchfilter($query) {
    if ($query-&gt;is_search) { //Are we here because of a search?
        $query-&gt;set('post_type',array('post','page')); //search BOTH pages AND posts...
        $zoe = htmlentities($query-&gt;get('s')); //Sanitize search text
        $query-&gt;set('s', $zoe) ; //Change search text (keyword) to cleaned version
    }
    return $query;
}

add_filter('pre_get_posts','searchfilter');

The comments explain what each line does.

This will allow WordPress search to find posts containing this special characters.

Class dismissed.

Leave a Reply