How can I get all subcategories and the posts related to it
$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 }?>
Note: this is a code for custom taxonomy and the code here exist in a file called taxonomy-($taxonomy_name)