是的,您可以使用meta_key
随着meta_value
参数其次,当没有特色帖子时,您需要两个查询:
查询特色文章/帖子:
$q = new WP_Query( [
\'post_type\' => \'post\',
\'meta_key\' => \'featured\',
\'meta_value\' => \'1\',
\'posts_per_page\' => 3,
\'no_found_rows\' => true,
] );
查询随机帖子:
$q = new WP_Query( [
\'post_type\' => \'post\',
\'orderby\' => \'rand\',
\'posts_per_page\' => 3,
\'no_found_rows\' => true,
] );
以下是一个示例:
$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:当不需要分页时,应始终设置
no_found_rows
到
true
. 此外,我假设您会使用标准的自定义字段编辑器或类似ACF的插件,为您的帖子添加/管理自定义字段。