In this post I’m addressing a shortcoming of WordPress’ built in search function.
[notice]
ADDENDUM: As of, well, sometime between this writing and 7/2016 the plugin JetPack has added this as a feature. I don’t know they do it the same way, but the following article is no longer correct when it states that WordPress does not handle special characters or that it limits it’s searching to only blog posts.
Even though this information is obsolete, I’ll leave it in place for historical purposes.
[/notice]
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, <, >, &, 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 & That but when you type “This & That” in the search box, it retains the “&” and does NOT transform it to & 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->is_search) { //Are we here because of a search? $zoe = htmlentities($query->get('s')); //Sanitize search text $query->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->set('post_type',array('post','page')); //search BOTH pages AND posts...
The resulting code should look like this
function searchfilter($query) { if ($query->is_search) { //Are we here because of a search? $query->set('post_type',array('post','page')); //search BOTH pages AND posts... $zoe = htmlentities($query->get('s')); //Sanitize search text $query->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