Make WordPress Core

Opened 11 years ago

Closed 11 years ago

#36227 closed defect (bug) (fixed)

get_categories does not return a valid wp_error

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

Description

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 11 years ago.
36227.diff​ (1.3 KB ) - added by boonebgorges 11 years ago.

Download all attachments as: .zip

Change History (6)

#1 @boonebgorges
11 years ago

  • Milestone Awaiting Review → 4.5
  • Version 4.4.2

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?

#2 @dd32
11 years ago

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

#3 @virgodesign
11 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
11 years ago

  • Owner set to boonebgorges
  • Resolution → fixed
  • Status new → 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.