With Genesis it’s super easy to highlight searched-for text on a webpage, which can be helpful to users hunting for information in text-heavy websites.
1) Create a customized version of search.php in your child theme, adding a couple of custom filters:
remove_action( ‘genesis_loop’, ‘genesis_do_loop’ );
add_action( ‘genesis_loop’, ‘mint_do_search_loop’ );
function mint_do_search_loop() {
$s = isset( $_GET[“s”] ) ? $_GET[“s”] : “”;
$args = (array(
‘s’ => $s,
‘post_type’ => array(‘post’,’page’),
‘posts_per_page’ => 6,
‘orderby’ => ‘title’,
‘order’ => ‘ASC’,
));
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
// remove post info.
remove_action( ‘genesis_entry_header’, ‘genesis_post_info’, 12 );
// remove post image
remove_action( ‘genesis_entry_content’, ‘genesis_do_post_image’, 8 );
// remove post content nav.
remove_action( ‘genesis_entry_content’, ‘genesis_do_post_content_nav’, 12 );
remove_action( ‘genesis_entry_content’, ‘genesis_do_post_permalink’, 14 );
// modify the links to pass the search params through to the page
add_filter( ‘get_the_content_more_link’, ‘mint_read_more_link’ );
add_filter( ‘genesis_post_title_output’, ‘mint_post_title_output’);
// remove entry footer.
remove_action( ‘genesis_entry_footer’, ‘genesis_entry_footer_markup_open’, 5 );
remove_action( ‘genesis_entry_footer’, ‘genesis_entry_footer_markup_close’, 15 );
remove_action( ‘genesis_entry_footer’, ‘genesis_post_meta’ );
// custom genesis loop with the above query parameters and hooks.
genesis_custom_loop( $args );
}
}
function mint_read_more_link() {
$s = isset( $_GET[“s”] ) ? $_GET[“s”] : “”;
return ‘<a class=”more-link” href=”‘ . get_permalink() . ‘?sp=’.$s.'”> …Read More</a>’;
}
function mint_post_title_output( $title ) {
$s = isset( $_GET[“s”] ) ? $_GET[“s”] : “”;
return ‘<h1 class=”entry-title”><a class=”more-link” href=”‘ . get_permalink() . ‘?sp=’.$s.'”>%s</a></h2>’;
}
2) The parameters can now be handled in the page template using the following:
$searchParam = ”;
if ( isset($_GET[‘sp’]) ) {
$searchParam = $_GET[‘sp’];
}
//highlight the output:
$text=get_the_content();
if($searchParam){
if (strpos(strtolower($text), strtolower($searchParam)) !== false){
//highlight
$highlight = ‘‘.$searchParam.’‘;
$text = str_replace($searchParam,$highlight,$text);
}
}
echo $text;
3) Finally, a miniscule amount of css:
.search-highlight{
background-color:yellow;
}