More
    HomeDesign / DevHighlight Search Terms Using jQuery

    Highlight Search Terms Using jQuery

    One way to spice up the search page is to highlight the search terms within the search results. The way described in this tutorial is using jQuery and will highlight both title and post content. Another way is not to use jQuery or using wordpress plugins which will not be describe in this tutorial.

    Find your theme’s functions.php file, and paste the following code:

    - Advertisement -

    [sourcecode language=’php’]

    function hls_set_query() {
    $query  = attribute_escape(get_search_query());
    if(strlen($query) > 0){
    echo ‘

    ‘;
    }
    }
    function hls_init_jquery() {
    wp_enqueue_script(‘jquery’);
    }
    add_action(‘init’, ‘hls_init_jquery’);
    add_action(‘wp_print_scripts’, ‘hls_set_query’);

    [/sourcecode]

    - Advertisement -

    After that manually you can open your theme’s header.php file and paste the following code before the </head> tag.

    [sourcecode language=’php’]

    [/sourcecode]

    Make sure to change the “post-area” in the code to the HTML tag ID (for eg: content or post) of the area you want your search terms highlighted. You can also change the way the highlighted text styles by changing the CSS properties of the “.hls” class.

    Enjoy!

    - Advertisement -
    WPTidBits
    WPTidBitshttps://wptidbits.com/
    Owner of WPTidBits. Totally in love with WordPress!

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here

    110FansLike
    761FollowersFollow