In my plugin code I would like to perform a WP_Query
(or similar) which returns all posts matching a given query string, as if the user typed that same string into the WordPress search form. Perhaps I’m just being dense, but I cannot seem to find a way to do so. I would expect to have a special parameter for WP_Query
, such as matching
, but I see no evidence of one.
I’ll start going through the WordPress codebase to see how it’s done internally, and I’ll post the answer here if I find it. I just thought someone might happen to know offhand.
Passing a query variable of “s” to
WP_Query
with a search term will filter post results by search term:The corresponding SQL
WHERE
clause generated by this query looks like this:Default search includes the wildcards as shown above, which is most likely what you’re looking for. If you want an exact search, you can also pass a query var of
"exact" => true
.For the details see the
get_posts
method ofWP_Query
in wp-includes/query.php.I use this in my plugin:
post_type
is needed if you’re going to work with custom post types.suppress_filters
will prevent the content from being formatted if you need to analyse it.posts_per_page
will return all posts, not the default per page.Something like this?
Or you could try this:
I believe you are looking is this
compare
from wordpress documentation
This is a simpler and easier way to do search: