The current project I am working left me needing to access the category ID (parent) and sub category ID for the sidebar.php
I have several sections in the sidebar for posts using is_single() that get the most popular posts, recent posts, etc. The problem using the code below – which works if you don’t deal with sub categories – is it only gets the parent category ID.
$categories = get_the_category(); $this_cat_ID = $categories[0]->cat_ID; $this_cat_name = $categories[0]->cat_name; $this_cat_url = get_category_link($this_cat_ID);
For example:
I have News category that has an ID of 6, a Press Release sub category with the ID of 7, and a TV Coverage sub category with the ID of 8.
The sidebar.php contains a block that displays the most recent posts.
If I am viewing a press release post (single.php) I want to see the the only latest Press Release posts. Using $this_cat_ID, which is the parent category ID, it is going to show all the posts in the News including not only Press Release but also TV Coverage.
It’s easy to get the parent category id as I showed above, and while it isn’t difficult to get the sub category ID (or IDs if you have more than one), most examples I found on the WP.org forums didn’t do what I needed. You need to add a few lines to get the sub cat.
$categories = get_the_category();
$this_cat_ID = $categories[0]->cat_ID;
$this_cat_name = $categories[0]->cat_name;
$this_cat_url = get_category_link($this_cat_ID);
// get the sub category if we have them
foreach ($categories as $cat) {
$parent = $cat->category_parent;
if ($parent != 0 ){
$sub_cat_ID = $cat->cat_ID;
$sub_cat_name = $cat->cat_name;
$sub_cat_url = get_category_link($sub_cat_ID);
}
}
With this code you still have access to the parent category ID but also gain the sub category ID.
All that is left is to just write a quick function that checks to see if there is a sub category, something that contains:
if (!$sub_cat_ID) {
echo $this_cat_ID;
} else {
echo $sub_cat_ID;
}
Problem solved! Now viewing a post filed under News will show the most recent News posts, a post filed under Press Coverage will show the most recent Press Coverage posts, and so on.
FYI – this method only works if you are going to have a post in one sub category at a time, otherwise you will have to modify things so the sub category info gets stuck in an array.
