Site logo

[Resolved] WP Search entire words not partial

Home Forums Support [Resolved] WP Search entire words not partial

Home Forums Support WP Search entire words not partial

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #2011657
    Marius

    Right now the search on my website is searching for partial words (searching for “and”, will return posts containing “andrew”, “land”).
    I tried using some functions found online but they all restrict the search to the title of the posts, ignoring the content.

    I would appreciate any help with a function that will allow the website to search for whole words, not partials, but without ignoring the content of the posts.

    #2011665
    Marius

    I found a function that seems to do the trick. I will leave it here, in case anyone else is looking for the same thing.

    add_filter( 'posts_search', 'my_search_is_perfect', 20, 2 );
    function my_search_is_perfect( $search, $wp_query ) {
        global $wpdb;
    
        if ( empty( $search ) )
            return $search;
    
        $q = $wp_query->query_vars;
        $n = !empty( $q['exact'] ) ? '' : '%';
    
        $search = $searchand = '';
    
        foreach ( (array) $q['search_terms'] as $term ) {
            $term = esc_sql( like_escape( $term ) );
    
            $search .= "{$searchand}($wpdb->posts.post_title REGEXP '[[:<:]]{$term}[[:>:]]') OR ($wpdb->posts.post_content REGEXP '[[:<:]]{$term}[[:>:]]')";
    
            $searchand = ' AND ';
        }
    
        if ( ! empty( $search ) ) {
            $search = " AND ({$search}) ";
            if ( ! is_user_logged_in() )
                $search .= " AND ($wpdb->posts.post_password = '') ";
        }
    
        return $search;
    }
    #2011681
    Leo
    Staff
    Customer Support

    Thank you for sharing!

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.