admin管理员组文章数量:1422488
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.
本文标签: get postsHow do I display an article using a WordPress custom field
版权声明:本文标题:get posts - How do I display an article using a WordPress custom field? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745356222a2655069.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论