我正在尝试创建一个带有多个类别的自定义主页。我知道这在WP_Query中是可能的,但我不想进行多次数据库访问。
发布于 2020-10-19 16:29:40
正如我在注释中所说的,如果每个类别需要5个(或一个特定的)帖子,那么您需要进行多个WP_Query
调用。否则,您可以使用类似于new WP_Query( [ 'cat' => '1,2,3,4' ] )
的内容,然后在显示这些帖子时将返回的帖子按其类别分组。
修改使没有任何帖子的类别不被显示。但请参阅我在下面备选案文2中的说明。
WP_Query
调用,每个类别有x个posts。// Category IDs. $cat_ids = [ 1, 2, 3, 4 ]; // For each category, query posts in that category, and just display them. foreach ( $cat_ids as $id ) { $query = new WP_Query( [ 'cat' => $id, 'posts_per_page' => 5, ] ); if ( $query->have_posts() ) { echo '' . esc_html( get_cat_name( $id ) ) . ''; echo ''; while ( $query->have_posts() ) { $query->the_post(); echo ''; the_title( '', '' ); // display other content you want echo ''; } echo ''; } wp_reset_postdata(); }WP_Query
。注:使用此选项,不能保证所有类别都在每个页面/请求中可用。但重点是,分组。也就是说,你会得到显示在他们自己的类别下的帖子。
// Category IDs.
$cat_ids = [ 1, 2, 3, 4 ];
// Get all posts that are assigned to any of the above categories.
$query = new WP_Query( [
'cat' => implode( ',', $cat_ids ),
'posts_per_page' => 10,
] );
// And then when displaying the posts, group them under their own category.
foreach ( $cat_ids as $cat_id ) {
$list = '';
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
if ( has_category( $cat_id ) ) {
$list .= '';
$list .= the_title( '', '', false );
$list .= 'add other content you want here..';
$list .= '';
}
}
}
if ( $list ) {
echo '' . esc_html( get_cat_name( $cat_id ) ) . '';
echo '' . $list . '';
}
wp_reset_postdata();
}
我希望这会有所帮助,只要把HTML修改成你喜欢的..。另外,我假设您所指的是默认的category
分类法;但是对于其他分类法,您可以使用has_tag()
或has_term()
来代替has_category()
,并且(例如,可以使用) get_term_field()
来获取术语/标记名。
https://wordpress.stackexchange.com/questions/376759
复制相似问题