If we pass a String to functions like get_posts
, and that string is not a meaningful querystring (for Example get_posts(‘ ‘)), the function returns the results of the default query (the last five posts or such).
Is it possible either to suppress this behaviour or – even better – to find out, if the string was a meaningful querystring or if the function just fell back to default hence it was not?
Changing the default query-settings is not a solution because I don’t want to affect the main loop, but only a function call of get_posts
in a plugin.
If you look at how the query works, this is not a case of …
What happens is that your conditions are merged with certain defaults via a very complicated sequence of conditionals. At the end of that, you have the
SQL
that runs to get your posts. The system doesn’t check to see if your conditions are “crap” and then decide to use them or not. Those conditions just get merged into the query in a way that generates a validSQL
statement. I am not sure how the query would know what is and isn’t “crap” anyway.The only thing I can think of doing would be to hook to
pre_get_posts
and check the query vars according to some set of conditions that you define to determine “crap” or “not crap”.As for the particular example you provide,
get_posts
is intentionally written to retrieve the latest post if not passed any arguments.new WP_Query('')
will not return anything, by the way, but essentially I agree with @toscho’s suggestion in a comment– pass a sanitized string. Know what you are sending to the function before you send it. If the string is empty or doesn’t meet some other requirement, don’t call theget_posts
function at all.