Skip to main content
2 of 3
Fix escaping of search string.
bonger
  • 4.4k
  • 1
  • 19
  • 25

You could try using several regexps to only search outside angle brackets:

function wpse159789_posts_search( $search, $query ) {
    if ( ! preg_match( '/wp_posts.post_content LIKE \'%(.+)%\'/', $search, $matches, PREG_OFFSET_CAPTURE ) ) {
        return $search;
    }
    $q_search = esc_sql( preg_quote( stripslashes( $matches[1][0] ) ) );
    $regexs = array();
    $regexs[] = '^' . $q_search;
    $regexs[] = '^[^<]+' . $q_search;
    $regexs[] = '<[^>]*>' . $q_search;
    $regexs[] = '<[^>]*>[^<]+' . $q_search;
    $regex = 'wp_posts.post_content RLIKE \'' . implode( '\' OR wp_posts.post_content RLIKE \'', $regexs ) . '\'';
    $search = substr( $search, 0, $matches[0][1] ) . $regex . substr( $search, $matches[0][1] + strlen( $matches[0][0] ) );
    return $search;
}
add_filter( 'posts_search', 'wpse159789_posts_search', 10, 2 );

I'm not sure this covers all cases, but seems to work on limited testing ... (it'd be a lot simpler if MySQL regexp supported look behind/ahead).

bonger
  • 4.4k
  • 1
  • 19
  • 25