开发者

Set Wordpress Post Subcategory to Variable

In the situation that I am viewing a wordpress post, I'd like to开发者_Go百科 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!


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)


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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜