get_the_category() definition clarification
-
Hi all,
I’ve been playing around with category icons, etc, and just wanted to check the use of get_the_category(). In the Codex Wiki, it says it returns an array of the categories associated with a given post_id. It also says that to retrieve the first category associated with a post, I might do
$cats = get_the_categories();
$first_cat= $cats[0];However, upon closer examination of both the source (function update_category_cache() in functions.php) and experiments, it seems that the array returned is indexed BY category ID. E.g., if categories 2 and 5 are set, then $cats[0] would be NULL, while $cats[2]->cat_ID would be 2.
Can someone confirm that this is the true behaviour? Or am I missing something? (Just wanted to make sure before I update the Wiki…) It seems like an odd way of doing it; more often I would think I would want to retrieve each category associated with a post, one after the other (which, of course, I could do with a foreach statement, but…) This method makes it easy for me to know whether a particular category is assigned to a given post, but what situations is that useful?
FWIW, my workaround is simply:
unset($post_cat);
foreach ((get_the_category()) as $cat){
$post_cat[] = $cat;
}which returns an integer indexed array of categories.
Cheers,
Joel
- The topic ‘get_the_category() definition clarification’ is closed to new replies.