Assume i have the following categories.
Movies
----- Action
----- Science fiction
----- Drama
Music
----- POP
----- Rock
Here, Movies and Music are the parent categories and rest of them are the subcategories.
If i want to display only the POP music ( posts for POP) from the Music category, How can I do that.
Please Help!.
I have no idea how to display posts from sub-categories. Only thing i have is an example code which can able to display Parent and subcategories posts.
<?
// Get the post ID
$id = get_the_ID();
//get all the categories ( this function will return all categories for a post in an array)
$category= get_the_category( $id );
if ($category->category_parent == 0) {
//extract the first category from the array
$catID = $category[0]->cat_ID;
//Assign the category ID into the query
$verticalNavigationSwitcher = "cat=$catID&orderby=ID&order=ASC";
}
$result = new WP_Query($verticalNavigationSwitcher);
//$featuredPosts->query('showposts=5&cat=3');
while ($result->have_posts()) : $result->the_post();
?>
<li><a href='<?php the_permalink() ?>'><span><?php the_title(); ?></span></a></li>
<?php
endwhile;
wp_reset_postdata();
?>
It looks like the example you are using over complicates things. If you simply need the posts from a particular category then you can use either the category slug or ID to retrieve the posts, and use WP_Query as in the above example.
So if the ‘Pop’ category has an id of 4 (you can get the category ID by hovering over the category name in Posts -> Categories…it’s shown in the edit link) then your code would be;
Here’s the relevant section from the Codex;
https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
I have found a way to show only one sub-category posts.
if I use “category__in” in my query, it is returning one category posts.