我想在首页显示3篇带有特定自定义字段的文章。文章需要包含“特色”字段,且值为true。
如果文章不存在,将显示3篇随机文章。
能否实现此功能?
我想在首页显示3篇带有特定自定义字段的文章。文章需要包含“特色”字段,且值为true。
如果文章不存在,将显示3篇随机文章。
能否实现此功能?
是的,您可以使用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的插件,为您的帖子添加/管理自定义字段。一切都好吗<我需要wp-list-table 也要显示custom-fields 在每个custom-post 我有,但我不知道如何做到这一点,在这幅图中,它显示了带有字段的表格:Title, Author and Publication Date: 我想要的是能够选择custom-fields 将出现,例如以下示例Title, Carta, Naipe, Author, and Date of Publication: