Instantly share code, notes, and snippets.

Embed
What would you like to do?
SearchWP's Term Highlight Extension does not automatically highlight terms in Supplemental Search Engine results templates, but it is easy to implement highlight functionality.
<?php
// this snippet is based on SearchWP's sample Supplemental Search Engine results template found here:
// https://searchwp.com/docs/configuration/#supplemental
// **************************** NOTE ****************************
// this snippet is just a portion of your search results template
// **************************** NOTE ****************************
// these are the search terms
$query = isset( $_REQUEST['swpquery'] ) ? sanitize_text_field( $_REQUEST['swpquery'] ) : '';
$highlighter = false;
if( class_exists( 'SearchWP_Term_Highlight' ) ) {
$highlighter = new SearchWP_Term_Highlight();
}
?>
<?php foreach ( $posts as $post ): setup_postdata( $post ); ?>
<div class="post">
<h2>
<a href="<?php echo get_permalink(); ?>">
<?php
// highlight the title
$title = get_the_title();
if( $highlighter ) {
$title = $highlighter->apply_highlight( $title, $query );
}
echo wp_kses_post( $title );
?>
</a>
</h2>
<?php
// output an excerpt
$excerpt = get_the_excerpt();
if( $highlighter ) {
$excerpt = $highlighter->apply_highlight( $excerpt, $query );
}
echo wp_kses_post( $excerpt );
?>
<div class="custom-field-content">
<?php
// output highlighted content from a Custom Field
$custom_field = get_post_meta( get_the_ID(), 'my_custom_field_key', true );
if( $highlighter ) {
$custom_field = $highlighter->apply_highlight( $custom_field, $query );
}
echo wp_kses_post( $custom_field );
?>
</div>
</div>
<?php endforeach; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment