正在尝试获取Wordpress主题中的帖子子类别



在我的wordpress网站上,我有一个部分只显示特定父类别中的文章摘录。每个帖子都有一个单独的子类别,我想把它也显示在标题和摘录旁边。

目前,我可以获得并提交所需的帖子,但每个帖子都显示了每个子类别,甚至是未分配给它的子类别。我如何修改它以只显示分配的子类别?

<div class="blog-items">
<?php
$args = array( 'posts_per_page' => 8, 'category' => 1 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post );
?> 
<div class="blue">    
<p><span>
<?php
$args2 = array('child_of' => 1);
$categories = get_categories( $args2 );
foreach($categories as $category) { 
$the_sub = $category->name;
echo $the_sub;
} ?>
</span></p>   
<h3><?php the_title(); ?></h3>  
<p><?php the_excerpt(__('(more…)')); ?></p>
<a href="<?php the_permalink() ?>">read more</a>
</div>
<?php endforeach; 
wp_reset_postdata();?>
</div>

编辑:

在Growdzens的帮助下,我最终做到了这一点。

<div class="blog-items">
<?php
$args = array( 'posts_per_page' => 8, 'category' => 1 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post );
?> 
<div class="blue">    
<p>
<span>
<?php
$categories = get_the_category( $post->ID);
foreach($categories as $category) { 
$the_sub = $category->name;
$cat1 = 4;
$cat2 = $category->cat_ID;
if( $cat2 != 1 ){
echo $the_sub;
}
}
?>
</span>
</p>   
<h3><?php the_title(); ?></h3>  
<p><?php the_excerpt(__('(more…)')); ?></p>
<a href="<?php the_permalink() ?>">read more</a>
</div>
<?php endforeach; 
wp_reset_postdata();?>
</div>

Wordpress有一个函数可以获取帖子的所有类别,您可以在这里阅读更多内容:get_the_category((

这个函数可以像下面的例子一样在循环中使用,以获得所需的结果。

<div class="blog-items">
<?php
$args = array( 'posts_per_page' => 8, 'category' => 1 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post );
?> 
<div class="blue">    
<p><span>
<?php
$categories = get_the_category( $post->ID);
foreach($categories as $category) { 
$the_sub = $category->name;
echo $the_sub;
} ?>
</span></p>   
<h3><?php the_title(); ?></h3>  
<p><?php the_excerpt(__('(more…)')); ?></p>
<a href="<?php the_permalink() ?>">read more</a>
</div>
<?php endforeach; 
wp_reset_postdata();?>
</div>

更新:要检查一个类别是否是特定其他类别的子类别,可以使用Wordpress函数cat_is_ancestor_of((

<div class="blog-items">
<?php
$args = array( 'posts_per_page' => 8, 'category' => 1 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post );
?> 
<div class="blue">    
<p><span>
<?php
$categories = get_the_category( $post->ID);
$parent_id = 4; //change this ID to the parent ID you want to show the subcategories for
foreach($categories as $category) { 
$the_sub = $category->name;
if(cat_is_ancestor_of( $parent_id, $category->cat_ID )){
echo $the_sub;
}
} ?>
</span></p>   
<h3><?php the_title(); ?></h3>  
<p><?php the_excerpt(__('(more…)')); ?></p>
<a href="<?php the_permalink() ?>">read more</a>
</div>
<?php endforeach; 
wp_reset_postdata();?>
</div>

最新更新