Hi @mian117,
I’d need to see some more of your code so I can help. How are you getting the current category ID exactly?
Hi @hcabrera,
Here is the code which gets the top-level category.
function smart_category_top_parent_id ($catid) {
while ($catid) {
$cat = get_category($catid);
$catid = $cat->category_parent;
$catParent = $cat->cat_ID;
}
return $catParent;
}
$postID = get_queried_object_id();
$category = get_the_category( $postID );
$catid = $category[0]->cat_ID;
$top_level_cat = smart_category_top_parent_id ($catid);
Alright, I’ll give that a test once I get some free time and report back.
One thing I’ll share right away -if you don’t mind some feedback- is that your smart_category_top_parent_id() function could use some minor code improvements.
Oh, one more thing. How do you usually categorize your posts? Do you assign both the parent category and the child category to a post? Just the child category?
I assign both, parent and child.
Following this…
Any updates @hcabrera
Thanks!
Nope, no updates unfortunately. Have been busy with work and so haven’t had the chance to get a test site up & running to test this yet @nextbracket.
Hey @mian117 & @nextbracket,
Sorry this took so long, it’s been a couple of busy weeks for me.
So I gave this some thought and came with a slightly different solution. Without further ado, it looks something like this:
<?php
function get_top_category($catid) {
$cat = null;
do {
$cat = get_category($catid);
$catid = $cat->cat_ID;
} while( $cat->category_parent );
return $cat;
}
if ( is_single() ) :
$postID = get_queried_object_id();
$category = get_the_category( $postID );
$catid = $category[0]->cat_ID;
$top_category = get_top_category($catid);
?>
<h2><?php printf( __('Most Popular In %s'), $top_category->name); ?></h2>
<?php
echo do_shortcode("[wpp cat='{$top_category->cat_ID}' limit=10 stats_views=0 stats_category=1 range='last24hours' thumbnail_width=157 order_by='views']");
endif;
?>
If you have any comments / questions please let me know.
Also, please keep in mind that:
- The code above will only work when viewing a post.
- The code assumes that all posts are assigned both the parent category(ies) and a child category (or multiple child categories).