问题描述
限时送ChatGPT账号..我想获得首页中唯一的顶级父类别(cat_id=1)列表.为此,我在主页中编写了这个 While 循环.
<?php而(有帖子()){the_post();?><div class="content-block col-xs-12"><h3><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h3><hr class="color-strip"><p><?php echo wp_trim_words(get_the_content(), 11);?></p><p><a href="<?php the_permalink(); ?>">继续阅读»</a></p><div class="tags"><ul><li><?php the_tags();?></li></ul></div><小时/><?php }?>
但它也带来了所有的子类别.我只想保留一个类别的列表.我必须在 if 条件中进行哪些更改.
解决方案您可以使用 get_categories()
并且您可以获得所有顶级类别:
$categories = get_categories(大批('父母' =>0));
然后,像这样的事情应该适合您只获取顶级类别中的帖子.
$categories = get_categories(大批('父母' =>0));$categoryArray = array();foreach( $categories 作为 $category ) {$categoryArray[] = $category->ID;}函数 exclude_category($query) {如果 ( $query->is_home() ) {$query->set('cat', implode(',', $categoryArray));}返回 $query;}add_filter('pre_get_posts', 'exclude_category');
这将获取所有顶级类别,然后在主查询中设置它们.
I want to get the only top parent categories(cat_id=1) list in the front page. For that I have written this While loop in home page.
<div class="left col-xs-12 col-md-8 col-lg-9">
<?php
while(have_posts()) {
the_post(); ?>
<div class="content-block col-xs-12">
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<hr class="color-strip">
<p><?php echo wp_trim_words(get_the_content(), 11); ?></p>
<p><a href="<?php the_permalink(); ?>">Continue reading »</a></p>
<div class="tags"><ul><li><?php the_tags(); ?></li></ul></div>
</div>
<hr/>
<?php }?>
</div>
But its bringing all the subcategories also. I want to keep the list of only one category. What change do I have to make in the if condition.
解决方案You can get the categories using get_categories()
and you can get all of the top level categories with:
$categories = get_categories(
array(
'parent' => 0
)
);
Then, something like this should work for you to get only posts within top level categories.
$categories = get_categories(
array(
'parent' => 0
)
);
$categoryArray = array();
foreach( $categories as $category ) {
$categoryArray[] = $category->ID;
}
function exclude_category($query) {
if ( $query->is_home() ) {
$query->set( 'cat', implode(',', $categoryArray) );
}
return $query;
}
add_filter('pre_get_posts', 'exclude_category');
This will get all of the top level categories and then set them in the main query.
这篇关于如何在wordpress中仅获取父类别帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论