If you are doing custom work on WordPress, you probably are using WP query. These is basically a database, essentially SQL, inside the WordPress template in order to deliver a highly customizable set of posts. With the ability to customize comes a bit of complexity.
One of the weird things that can happen is that a WP query that should yield no results will sometimes return many results. How do you fix this?
Perhaps your wp query looks a bit like this…
$args = array(
'posts_per_page'=> 10,
'post_type' => 'customPostType',
'meta_key' => 'customFieldName',
'meta_value' => $myVariable,
);
$the_query = new WP_Query( $args );
After that you can if( $the_query->have_posts())
and do the stuff you want to do, usually print a list of posts.
Say you are doing something like working with kitchen appliances, and you are looking for matched pairs of appliances, it’ll be really clear if a unit matches with another or not. And there will never be a circumstance under which one appliance matches with 10 others, so when a query has multiple results you know something is wrong.
What’s the fix? It turns out that the query wants (in a manner of speaking) to return results so you need to give it an alternative solution — an else. A nice way to do this looks like…
$args = [
'posts_per_page' => 10,
'post_type' => 'customPostType',
];
if ( ! empty( $pairedThing ) ) {
$args['meta_key'] = 'customFieldName';
$args['meta_value'] = $myVariable;
}
Basically you have the same query, but the if
statement means there is a specified outcome for when no results come back. Now you can build an else
into the rest of function. In other words, print the returned list of posts or
simple print “Nothing found!”
This might seem like PHP for beginners or WordPress for amateurs, but I’ve found it to be a pretty handy solution. I haven’t had a lot of circumstances, within WordPress development, where I needed an if statement in an wp or meta query, but is good to know how to do it.
Perhaps the more interesting question is why results were returns when there should have been none. I’m not 100% sure why this is happening, but of course the best practice would be to always have a outcome for circumstances under which a query will fail and to accomodate that failure in an elegant manner — not simply to assume a failure will return null and nothing bad or unexpected will happen.
Sal December 31st, 2021
Posted In: Web Development