Getting the top-level parent
After hearing a lot of rave reviews, I decided to use WordPress as the blogging system for The Y-Factor. I’ve spent some time over the past couple of weeks tweaking WordPress to get it to do exactly what I want it to. It’s somewhat intimidating to get started with, but taking it a step at a time, I got to where I want to be.
One of the challenges I faced was finding the root category (the top-most category in the category tree) for any given post. Specifically, I wanted this so I can determine which “section” of The Y-Factor the reader is in – work, life, or photo blog. Based on that, I can select certain elements in the top navigation, as well as customize the links in the right navigation. One would think that there would be a simple function that already exists in WordPress to go this, but that’s not the case, so I wrote one. Keep in mind that given that WordPress only allows a single parent for each category, this shouldn’t be too hard – it simply involves traversing up the category tree until to find a category that has no parent. I was surprised to see this didn’t exist and figured that this is probably useful to others as well since I saw several people asking for it, but no solution. So, here’s my code:
$parent_cats = get_category_parents($category_id);
$split_arr = split(“/”, $parent_cats);
Paste the above code into the functions.php file. You can either paste it in the functions.php file in the wp-includes directory, or in the wp-content/themes/<your_theme_name> directory. I put it in the former since I didn’t want the function disappearing whenever the theme was changed. Once you’ve got that in place, you simply call the function, giving it the category ID for the category whose root parent you want to find. The function will either return the root parent, or 0 if it can’t find one. If you give this function the category ID of a root category, it’ll simply return that ID to you.
Hopefully this helps some other WordPress users out there. If you have any questions, please leave comments and I’ll get back to you…