I am trying to make a custom sidebar for my posts in certain categories. It will look something like this.
My category structure looks like this:
- Parent 1
- Child 1
- Sub Child 1
- Sub Child 2
- Child 1
- Sub Child 1
- Sub Child 2
- Child 1
- Parent 2
What I want to do is to display all posts under Sub Child 1 and 2. I will be more specific, lets say we have 3 posts, 2 of them is under sub child 1 and last one is under sub child 2. Then I only want the 2 posts that is under sub child 1 to be displayed under Sub child 1, and the 3 :rd post to display only under sub child 2.
I have been looking in 2 days now over the Internet to figure this out how to do this, but I dont get what I am doing wrong.
Here is my code and what I am trying to modify:
<?php
$cat = get_the_category();
$catID = get_cat_ID($cat);
$subcats = get_categories('child_of=' . $catID);
foreach($subcats as $subcat) {
echo '<h3>';
echo '<a href="' . get_category_link($subcat->cat_ID) . '">';
echo '/' . $subcat->cat_name . '';
echo '</a></h3>';
echo '<ul>';
$subcat_posts = get_posts('cat=' . $subcat->cat_ID);
foreach($subcat_posts as $subcat_post) {
$postID = $subcat_post->ID;
echo '<li>';
echo '<a href="' . get_permalink($postID) . '">';
echo get_the_title($postID);
echo '</a></li>';
}
echo '</ul>';
}
?>
Any ideas?
I guess you could take a big step using
wp_list_categories()
with awalker
to add a additional Unordered List to every item.The code:
Finally, after searching all day .. collecting & combine the code.. this is it :
enjoy it 🙂
Function for getting all categories and their post for a particular parent category