2

I am working on a wordpress site and I am using wordpress native search. When we search for a string like "example" it searches inside html tags. ie if there is any html tag like <a href="http://example.com"> in the page or post then the search result will show that particular page or post. I dont want to search inside html tags.

I already tried using the plugin Search Exclude HTML Tags But it uses MySql stored function which is not working for me. I think it may be issue with the permission of my mysql user.

Is there any alternate way to fix this.

Thanks Pramod

2 Answers 2

0

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

function wpse159789_posts_search( $search, $query ) {
    global $wpdb;
    if ( ! preg_match( '/' . $wpdb->posts . '\.post_content LIKE \'%(.+)%\'/', $search, $matches, PREG_OFFSET_CAPTURE ) ) {
        return $search;
    }
    $search_str = stripslashes( $matches[1][0] );
    // Cater for closed angle pairs embedded in the search string.
    for ( $i = 0, $len = mb_strlen( $search_str ); $i < $len; $i++ ) {
        $q_searches[] = '(<[^>]*>)?' . preg_quote( mb_substr( $search_str, $i, 1 ) );
    }
    $q_search = implode( '', $q_searches );
    $regexs[] = '^[^<]*' . $q_search; // Before any angle bracket.
    $regexs[] = '(<[^>]*>)[^<]*' . $q_search; // After any closed angle bracket pair.
    array_unshift( $regexs, implode( ' OR ', array_fill( 0, count( $regexs ), $wpdb->posts . '.post_content RLIKE %s' ) ) );
    $search_replace = call_user_func_array( array( $wpdb, 'prepare' ), $regexs );
    $search = substr( $search, 0, $matches[0][1] ) . $search_replace . substr( $search, $matches[0][1] + strlen( $matches[0][0] ) );
    return $search;
}

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).

0

I created a tiny plugin for this :) and fixed the issue.

https://wordpress.org/plugins/wp-search-ignore-html-tags/

Just one or 2 lines of code. Worked in most cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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