Handling special HTML characters in visitor searches
-
I have “Trainz” content on my site, and such content uses coded numbers for identification as follows <KUID:123456:654321>. So I post the information to my pages with that identifier in the body of the page.
This results in the page having <KUID:123456:654321> however if someone used the search box on my site, the search was executed with < and > in the search and not the html encoded version.
To fix this, I did the following in my theme’s functions.php
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, change < etc. to < $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.
Hope this helps someone else some day.
- The topic ‘Handling special HTML characters in visitor searches’ is closed to new replies.