[wp-hackers] Problem getting categories

Otto otto at ottodestruct.com
Mon May 10 17:46:05 UTC 2010


On Mon, May 10, 2010 at 12:33 PM, Brian Fidler <fidler.brian at gmail.com> wrote:
> I'm working on an artists website where I have categories set up like this:
>
> Paintings
>   -collection1
>   -collection2
>
> Prints
>   -collection3
>   -collection4
>
> Once I have the category I want to loop through all posts in that category
> to grab a custom field from each post.
>
> my url string looks like this:
>
> http://www.mysite.com/paintings/collection1/post-name
> http://www.mysite.com/prints/collection3/post-name
>
> I'm trying to get the categories using this:
>
> $categories = get_the_category($post->ID);
> echo $categories[0]->cat_name;
>
> It gets the parent category (category[0]) without any problem however it
> isn't getting child categories at all.
>
> What am I doing wrong?


Firstly, the category in the URL string is irrelevant. You'll find
that a URL of http://www.mysite.com/paintings/bippyboppity/post-name
will work just as well.

Secondly, get_the_category will get the categories assigned to the
post itself. But while categories are indeed hierarchical, the
hierarchy only applies to the categories themselves, not to the posts
in those categories.

That is, if you have parent->child categories, and you put a post into
child, then it is NOT also in parent. Categories are like tags, if you
want a post to be in a category, you must explicitly put it in that
category. It doesn't inherit any hierarchy from the category tree.

-Otto


More information about the wp-hackers mailing list