0

I am attempting to add highlighting to my search results in the theme that I am coding. I found the way to do it on this thread: How to highlight search terms without plugin and it worked wonderfully. However, it is conflicting with my read more link whenever a permalink contains the search term by trying to do the replacement in the read more link causing the link to break oddly.

Does anyone have a suggestion or fix for it?

The following codes I use are as follows:

function search_excerpt_highlight() {
    $excerpt = get_the_excerpt();
    $keys = implode('|', explode(' ', get_search_query()));
    $excerpt = preg_replace('/(' . $keys .')/iu', '<ins class="search-highlight">\0</ins>', $excerpt);
    echo '<p>' . $excerpt . '</p>';
}

function supralegal_auto_excerpt_more( $more ) {
    return '&hellip;' . supralegal_read_more_link();
}
add_filter( 'excerpt_more', 'supralegal_auto_excerpt_more' );

function supralegal_read_more_link() {
    return ' <a href="'. esc_url( get_permalink() ) . '" class="read_more">' . __( 'Read more', 'supralegal' ) . '</a>';
}
0

Try this.

function search_excerpt_highlight() {
    $excerpt = get_the_excerpt();
    $keys = implode('|', explode(' ', get_search_query()));
    $excerpt = preg_replace('/(' . $keys .')/iu', '<ins class="search-highlight">\0</ins>', $excerpt);
    echo '<p>' . $excerpt . '&hellip;' . supralegal_read_more_link() . '</p>';
}

function supralegal_auto_excerpt_more( $more ) {
    return '';
}
add_filter( 'excerpt_more', 'supralegal_auto_excerpt_more' );

function supralegal_read_more_link() {
    return ' <a href="'. esc_url( get_permalink() ) . '" class="read_more">' . __( 'Read more', 'supralegal' ) . '</a>';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.