I’m working on a website with a search feature that allows users to search through a lot of post meta. There is a specific search pattern that I would like to forcibly return no results for. The WP_Query technically will find results in the database, but I’d like to override that somehow to force it to return no results to trigger the if( $example->have_posts() )
to fail.
Is there some sort of parameter I can pass to WP_Query like 'force_no_results' => true
that will force it to return no results?
Try
Simple and to the point.
Update:
Curiously there is no clean/explicit way to short circuit
WP_Query
.If it’s main query you might work something out around
WP->parse_request()
, there seems to be relatively recent (3.5)do_parse_request
filter there.But for
WP_Query
itself dirty hacks are usually in order, such as short-circuiting SQL query by addingAND 1=0
viaposts_where
filter, etc.The problems on set a query parameter to unexistent value are 2:
'posts_*'
filter hooks ('posts_where'
,'post_join'
, etc..) that act on query, so you can never be sure that even setting unexistent param the query return no results, a simpleOR
clause returned by a filter make return something.You need a little bit hardcore routine to be sure a query return no result and there is no (or very minimun) performance issue.
To trigger that routine, you can use every method, technically you can pass any argument to
WP_Query
, event arguments that doesn’t exists.So if you like something like
'force_no_results' => true
, you can use it like so:and add a callback running on
'pre_get_posts'
that do the hard work:What this code does is run on
'pre_get_posts'
as late as possible. If the argument ‘force_no_results’ is present in the query, then:SELECT ID FROM wp_posts WHERE 0 = 1
once all filters are removed, there is no possibilities this query is changed and it is very fast, and has no result for sure