I want to display 3 articles with specific custom fields on the front page. The article needs to contain "featured" fields and the value is true.
If the article does not exist, 3 random articles are displayed.
Can this function be implemented?
I want to display 3 articles with specific custom fields on the front page. The article needs to contain "featured" fields and the value is true.
If the article does not exist, 3 random articles are displayed.
Can this function be implemented?
Share Improve this question edited Jul 1, 2019 at 2:52 fuxia♦ 107k39 gold badges255 silver badges459 bronze badges asked Jul 1, 2019 at 1:58 MatthewMatthew 1515 bronze badges 3- Yes, sure it can. But you could also use Tag or Category than custom field. – Sally CJ Commented Jul 1, 2019 at 2:13
- What do I need to do? There is a downside to using tags and categories, which adds a publicly accessible archive link. – Matthew Commented Jul 1, 2019 at 2:20
- There are actually filters/hooks you can use to exclude certain terms from the public, including restricting access to a specific term's archive page. Nonetheless, see my answer for retrieving and displaying the featured posts by custom field. – Sally CJ Commented Jul 1, 2019 at 3:22
1 Answer
Reset to default 0Yes, 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.