Yes, and you can use the meta_key
along with meta_value
parameter. Secondly, you’re going to need two queries when there are no featured posts:
-
Query the featured articles/posts:
$q = new WP_Query( [ 'post_type' => 'post', 'meta_key' => 'featured', 'meta_value' => '1', 'posts_per_page' => 3, 'no_found_rows' => true, ] );
-
Query random posts:
$q = new WP_Query( [ 'post_type' => 'post', 'orderby' => 'rand', 'posts_per_page' => 3, 'no_found_rows' => true, ] );
Here’s an example:
$q = new WP_Query( [
'post_type' => 'post',
'meta_key' => 'featured',
'meta_value' => '1',
'posts_per_page' => 3,
'no_found_rows' => true,
] );
// No featured posts.
if ( ! $q->have_posts() ) {
$q = new WP_Query( [
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 3,
'no_found_rows' => true,
] );
echo 'Displaying random posts.'; // test
} else {
echo 'Displaying featured posts.'; // test
}
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
// Display the post.
the_title( '<h3>', '</h3>' );
//...
}
}
PS: When pagination is not needed, you should always set the no_found_rows
to true
. Also, I’m assuming you’d use the standard custom fields editor or a plugin like ACF, to add/manage the custom field to/for your posts.