Back in December, I posted about how I generated a random post of the day.
After running it for 60 days, I realized I needed to exclude three things:
- Posts with a specific ‘placeholder’ image
- Posts with content ‘TBD’
- Posts with one of two specific meta values
So today we will talk about how awesome WP_Query is.
The Basic Query
As a reminder, your basic query for a random post is this:
$args = array( 'post_type' => 'posts', 'orderby' => 'rand', 'posts_per_page' => '1' ); $post = new WP_Query( $args );
Now, let’s extend it!
Posts With An Image
In this example, I have a very specific default image I use – the mystery person – to indicate the post doesn’t have it’s own image yet. I went and found the image in my media library and took note of the value – 949. Then I added a meta query which said “If the _thumbnail_id
does not equal 949.”
'meta_query' => array( array( 'key' => '_thumbnail_id', 'value' => '949', // Mystery Person 'compare' => '!=', ),
Seriously. It’s magic.
Posts Without ‘TBD’
We also have a standard convention for when we have a pending data post, but we need it for statistical reasons. Since, as of WP 4.4, you can use negatives in searches, just add this to the basic query:
's' => '-TBD',
This could be useful for your stores, if you wanted to list a product of the day but perhaps not ones with “Coming Soon” in the description. Of course, you should also have some meta flag but you get the idea.
Posts With One of Two Values
Okay. Here’s fun. Let’s say you have a post meta field called example_site_group
and there are six choices in it but you only want one and two. Well, for that you need to use an array and a LIKE:
'meta_query' => array( array( 'key' => 'example_site_group', 'value' => array ( 'baseone', 'basetwo' ), 'compare' => 'LIKE', ),
This is a little messier, but it certainly does work. Even with serialized data.
Put It All Together
Here’s the real code:
// Grab a random post $args = array( 'post_type' => 'post_type_characters', 'orderby' => 'rand', 'posts_per_page' => '1', 's' => '-TBD', 'meta_query' => array( array( 'key' => '_thumbnail_id', 'value' => '949', // Mystery woman 'compare' => '!=', ), array( 'key' => 'lezchars_show_group', 'value' => array ( 'regular', 'recurring' ), 'compare' => 'LIKE', ), ) ); $post = new WP_Query( $args );
And voila.