tags:

views:

23

answers:

2

Hi all,

In the situation that I am viewing a wordpress post, I'd like to be able to identify only the subcategory that the post is in and set that subcategory as a variable. I can't seem to find any easy way to do this. Can anyone help?

Example: I'm viewing a baseball blog post under a sports category - but I want to only set the subcategory "baseball" as my variable.

I would like to do this for any category that has subcategories.

Thanks!

+1  A: 

I'm not sure I understand your question. But I think it goes like this;

You have a category called Sports. A sub-category is Baseball.

When you open a baseball blog post, you want to retrieve this category.
You can do this by using get_the_category function.
http://codex.wordpress.org/Function_Reference/get_the_category

So this would get you all the categories for the current post.

$categories = get_the_category();
echo $categories[0];

And if I remember correctly, the first category selected for this post, will be it's main category and thus be the first in the list (if multiple categories are selected)

Steven
I know to echo $categories[0], I must actually refer to the cat_name as well, to be more specific about what I'm trying to print. The issue with this technique is that that order of the categories in the list is only determined by alphabetical order, not by main category first and subcategory second. But yes, I am trying to grab that subcategory value as you've determined.
Dave Kiss
If I read correctly, this function does not include parent categories. Ergo, first category is the one you would want (if I understand you right).
Steven
A: 

I figured it out, but you set me in the right direction. I basically just needed to check to see if a category had a parent, and if it did, it was a subcategory.

// This code retrieves a single post's subcategory and sets a variable for it.
if (is_single() ){
    $single_post_categories = get_the_category();
    $single_post_parent_category_check = $single_post_categories[0]->category_parent;
    if ($single_post_parent_category_check != '0') {
        $single_post_subcategory = $single_post_categories[0]->cat_name;
    }
    else {
        $single_post_subcategory = $single_post_categories[1]->cat_name;
    }
}
Dave Kiss