[wp-trac] [WordPress Trac] #36878: get_term_by returns random result with multiple terms

WordPress Trac noreply at wordpress.org
Fri May 20 19:43:26 UTC 2016

#36878: get_term_by returns random result with multiple terms
 Reporter:  cogmios                     |       Owner:
     Type:  defect (bug)                |      Status:  new
 Priority:  normal                      |   Milestone:  Future Release
Component:  Taxonomy                    |     Version:  4.5.2
 Severity:  normal                      |  Resolution:
 Keywords:  needs-patch good-first-bug  |     Focuses:  docs
Changes (by boonebgorges):

 * keywords:   => needs-patch good-first-bug
 * focuses:   => docs
 * milestone:  Awaiting Review => Future Release


 Hi @cogmios - Thanks very much for the ticket and for the clear
 explanation of the issue.

 A quick note about the history of this issue. Before WP 4.1 or
 thereabouts, this problem would only arise in cases where two terms were
 in different branches of a hierarchical taxonomy, because it wasn't
 possible (through WP's functions, anyway) to create two terms with the
 same names in any other way, at least not within the same taxonomy. And
 since `get_term_by()` always required a `$taxonomy` argument, the problem
 would arise fairly rarely.

 Versions 4.1 through 4.3 eased some of these requirements - it's now
 possible for duplicate names, and even slugs, to exist in certain cases,
 both within and between taxonomies. And in WP 4.4, the `$taxonomy` param
 was made optional, meaning that the possibility for ambiguity arose even
 more - not just with names, but also slugs, since terms in different
 taxonomies can share a slug.

 I'm not sure that we can change the default return value of
 `get_term_by()` to be either a `WP_Error` object or an array. Consider the

 $term = get_term_by( 'name', 'foo' );
 if ( $term ) {
     echo $term->name;

 This will break if we return a non-falsey value that is not a `WP_Term`.
 Even in core, we do this in many spots. Plugins probably do it in
 thousands of ways.

 We could potentially add another parameter (or another value of the
 `$output` parameter) that tells `get_term_by()` to return an array of
 terms. But in that case, we're really just reproducing `get_terms()`,
 which people ought to be using anyway when they might be expecting
 multiple results.

 I think the best we can do here is a note in the documentation that warns
 people of this danger, and suggests that they use `get_terms()` (or at
 least to specify the `$taxonomy`) when there's the potential for conflict.

Ticket URL: <https://core.trac.wordpress.org/ticket/36878#comment:1>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform

More information about the wp-trac mailing list