How to tune search argument in WP_Query to show only exactly the same results?

Right now I am using this:

$args_search = array( 
    's' => $search,
    'post_type' => array( 'post' )
);

$wp_query = new WP_Query( $args_search );

But the problem is that it shows everything.

Read More

E.g. if $search is just "2386" and I have in my db 3 posts:

"12386111"
"23861111"
"11112386"

I will get 3 results.

But I want to get 0 results. because it’s not a full match.

Only if the search is 23861111 then I need to get the 1 result 23861111.

Or when it is 11112386 I need to type the full 11112386 as a $search variable and not only 2386 or 238 to get the result 11112386

How to change my query to get the results as I want instead of everything that contains the search string?

Related posts

1 comment

  1. $args_search = array( 
        's' => $search,
        'exact' => 1,
        'post_type' => array( 'post' )
    );
    

    There is no docs in Codex for ‘exact’ param, but best (sure the most reliable) docs is the code itself. See the line 2200 of query.php

    A limitation: if you have spaces on the search argument it will not work, because WP_Query consider search term with spaces as different search terms.

    So maybe you can use:

    $args_search = array( 
        's' => $search,
        'post_type' => array( 'post' )
    );
    // if no spaces in search we put exact argument
    if ( count(explode(' ', $search)) == 1 ) $args_search['exact'] = 1;
    

    A note on your code. Right 'post_type' => array( 'post' ) not ‘posts’ (plural) as you posted.

Comments are closed.