获取所有子类别和相关帖子

时间:2019-01-02 作者:Nader Elsayed

如何获取所有子类别以及与之相关的帖子

 $term = get_queried_object();
    if($term->post_parent !=0 ){ 

    //  echo \'has parent\'; //this post category has child
    $term_id = $term->term_id;
    $taxonomy_name = $term->taxonomy;
    $termchildren = get_term_children( $term_id, $taxonomy_name );
     // echo    $postcat ;
     foreach ($termchildren  as $child) {
    $term = get_term_by( \'id\', $child, $taxonomy_name );
             ?>
             // get the categories and if have subcategory get it 


             <?php }?>



     <?php   }
     else{
          //the posts in a subcategory 
    while(have_posts()):the_post();
       // get the subcategory posts

<?php endwhile ?>
<?php  }?>
注意:这是自定义分类法的代码,这里的代码存在于名为taxonomy的文件中($taxonomy\\u name)

1 个回复
SO网友:Md. Ehsanul Haque Kanan

尝试使用以下代码:

if( isset( $sub_category ) ){ 
 echo \'<b>more items in: </b>\' . $sub_category->name;
 $args = array(
 \'cat\' => $sub_category->term_id,
 \'post__not_in\' => array( get_the_ID() )
 );
 $relatedpostsinsubcategory = new WP_Query( $args );
 if( $relatedpostsinsubcategory->have_posts() ){
 while( $relatedpostsinsubcategory->have_posts() ){
 $relatedpostsinsubcategory->the_post();

 ?>
 <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> 
<?php
 }
 wp_reset_postdata();
 }
}
您可以找到有关获取子类别和相关帖子的更多信息here.