Posted on

Scroll result page to the search term

Relevanssi can highlight search terms on the posts (which is a feature I generally don’t recommend, as it may lead to some compatibility issues). But how about scrolling the page to show the location where the search results are? That is also possible.

It requires a bit of JavaScript on the post page.

This script needs to run on the post page:

<script>
jQuery(document).ready(function($) {
	$.extend($.expr[":"], {
		"containsNC": function(elem, i, match, array) {
			return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
		}
	});
 
	var mySearchString = getParams("hilite");
	var offsetToWord = $("p:containsNC('" +mySearchString + "'):last").offset().top;
 
	$("html, body").animate({ scrollTop: offsetToWord }, 0);
 
	function getParams(param) {
		var vars = {};
		window.location.href.replace( location.hash, '' ).replace( 
			/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
			function( m, key, value ) { // callback
				vars[key] = value !== undefined ? value : '';
			}
		);
		return vars[param];
	}
});
</script>

The easiest way is to just add this to the single post template, but the right way is to use wp_enqueue_script(). Now the post page will automatically scroll to the location of the search term, taken from the “hilite” query parameter. The scroll is instant; if you want to make it slower, increase the 0 in $("html, body").animate({ scrollTop: offsetToWord }, 0); to 1000 or 2000 to get a slower animation.

Now all you need is the search term in the “hilite” parameter. On your search results template, you likely have something like this:

<a href="<?php the_permalink(); ?>"><?php _e( 'Read More', 'total' ); ?></a>

Change it to this to append the search query to the URL:

<a href="<?php the_permalink(); ?>#hilite=<?php echo get_search_query(); ?>"><?php _e( 'Read More', 'total' ); ?></a>

This is a fairly brutal method and probably lacks all sorts of necessary finesse, but it’s a start.

  • Martin Cooper

    Search to return EXCERPTS – Genesis Outreach Pro.

    There is no access to a search.php in the backend of Outreach pro.
    I am not a developer but have dappled successfully with my functions PHP – shortcodes, etc.

    My problem is that I cannot find where to add the excerpts() command, to force my searches to return a predetermined number of lines from relevant pages. ATM, I am getting impossibly full page dumps. I tried functions.php but to no avail.
    Could somebody please advise where and what code I should be adding to enable Relevanssi to return excerpts of pages. I have few posts; my site is almost entirely comprised of pages.

    Much appreciated.
    Martin Cooper

    • See Genesis theme archive settings. If your archives are set to display excerpts, search results will also display them. Here’s another solution: https://gist.github.com/nutsandbolts/7377351

      • Martin Cooper

        It worked! Your response time was exceptional, Mikko.

        I am extremely impressed.

        Cheers from Australia.