Make WordPress Core

Opened 8 years ago

Closed 8 years ago

#36227 closed defect (bug) (fixed)

get_categories does not return a valid wp_error

Reported by: virgodesign's profile virgodesign Owned by: boonebgorges's profile boonebgorges
Milestone: 4.5 Priority: normal
Severity: normal Version:
Component: Taxonomy Keywords:
Focuses: Cc:


The get_categories() function does not return a valid wp_error object if an invalid taxonomy is passed in as a parameter.
For "invalid taxonomy" we can consider a taxonomy that does not exists or a taxonomy that is not yet registered.

As reported here: get_categories() is a wrapper for get_terms().

And get_terms return a wp_error object if fails.

BUT, inside the get_categories() function there is this casting:

$categories = (array) get_terms( $taxonomy, $args );

This type of casting convert the wp_error object into an array, losing the ability to recognize the error using is_wp_error() function.

I think this should be a bug.

Attachments (2)

36227.patch (1.7 KB) - added by sebastian.pisula 8 years ago.
36227.diff (1.3 KB) - added by boonebgorges 8 years ago.

Download all attachments as: .zip

Change History (6)

#1 @boonebgorges
8 years ago

  • Milestone changed from Awaiting Review to 4.5
  • Version 4.4.2 deleted

Yes, definitely a bug.

However, I don't think that returning a WP_Error object is a wise solution. As far as I can see, get_categories() has always returned nothing but an array. Changing this now is likely to cause compatibility problems. And in any case, it's a convenience wrapper for get_terms() that does nothing much aside from _make_cat_compat(); and _make_cat_compat() only makes sense when you're fetching category terms, yet when you're fetching category terms you won't get a WP_Error. As such, if you need proper error reporting, and you're not fetching category terms, just use get_terms().

See 36227.diff. Anyone see a problem with this?

8 years ago

#2 @dd32
8 years ago

36227.diff looks like the expected and intended behaviour of the function.

#3 @virgodesign
8 years ago

I agree with @boonebgorges. This ensure consistency and compatibility.
A user can always check if the returned array is empty before attempt to access its content.

#4 @boonebgorges
8 years ago

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

In 36988:

Improve error handling in get_categories().

When passed an invalid 'taxonomy', get_terms() will return a WP_Error
object. This object should not be blindly cast to an array. Instead, an empty
array should be returned, to indicate that no matching terms have been found.

Props virgodesign, sebastian.pisula.
Fixes #36227.

Note: See TracTickets for help on using tickets.