WordPress.org

Make WordPress Core

Opened 3 years ago

Closed 3 years ago

#15442 closed defect (bug) (fixed)

Indexes no longer start at 0 for get_the_category()

Reported by: ramenboy Owned by:
Milestone: 3.1 Priority: normal
Severity: normal Version: 3.1
Component: General Keywords: has-patch
Focuses: Cc:

Description

Due to changes related to #15407, it seems that the keys in the array returned by get_the_category() are now category IDs instead of being 0-based. As a result, code such as the following now breaks:

<?php
$category = get_the_category();
echo $category[0]->cat_name;
?>

The above usage is from the docs: http://codex.wordpress.org/Function_Reference/get_the_category

Attachments (2)

15442.diff (489 bytes) - added by greuben 3 years ago.
untested
15442-2.diff (481 bytes) - added by greuben 3 years ago.
based on IRC discussion

Download all attachments as: .zip

Change History (12)

comment:1 filosofo3 years ago

Don't you think it would be better just to change the docs?

comment:2 nacin3 years ago

Unfortunately I am betting this is common usage.

comment:3 gazouteast3 years ago

  • Cc gazouteast added

Possibly related, but certainly a side effect
http://wordpress.org/support/topic/yet-another-category_id-how-to-thread?replies=1

Multiple issues surfacing -

$category = get_the_category(); = fails to get the category ID numbers
echo $category[0]->cat_name; = (tested on two different servers now) the " -> " is being read as the closer for a " <!-- " HTML comment tag.

The context I'm trying to use this in, is in the sidebar, in a widget, to grab the category ID number and assign it to a variable for use in a function call. In this instance, it's a new build where the category number, Adrotate group and block, and the NextGEN gallery ID numbers are all synchronised such that ID 1 = name Art in all cases. But, the category ID call is failing and blocking the build from progressing.

I'm not submitting this as a support shout, but rather to give you an instance of failure. The initial ticket report now gives me a clue as to why.

comment:4 nacin3 years ago

  • Milestone changed from Awaiting Review to 3.1

greuben3 years ago

untested

comment:5 greuben3 years ago

  • Keywords needs-testing added

comment:6 nacin3 years ago

In the wild: #15776

greuben3 years ago

based on IRC discussion

comment:7 scribu3 years ago

If we do decide to use array_values(), maybe it should be called further down, in get_the_terms() ?

comment:8 nacin3 years ago

I imagine that would then break backwards compatibility for those using get_the_terms() and expecting term ids as indicies.

comment:9 scribu3 years ago

  • Keywords has-patch added; needs-testing removed

Right, nevermind then.

comment:10 scribu3 years ago

  • Resolution set to fixed
  • Status changed from new to closed

(In [16888]) Re-index categories in get_the_category(). Props greuben. Fixes #15442

Note: See TracTickets for help on using tickets.