Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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>';
}
share|improve this question

1 Answer 1

up vote 0 down vote accepted

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>';
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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