WordPress.org

Ready to get started?Download WordPress

Forums

Handling special HTML characters in visitor searches (1 post)

  1. yorokobi
    Member
    Posted 1 year ago #

    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 &lt;KUID:123456:654321&gt; 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.

Topic Closed

This topic has been closed to new replies.

About this Topic