WordPress.org

Make WordPress Core

Opened 7 years ago

Closed 7 years ago

#7181 closed defect (bug) (fixed)

in_category returns erroneous results for non-cached categories

Reported by: fshowalter Owned by:
Milestone: 2.7 Priority: normal
Severity: normal Version:
Component: General Keywords:
Focuses: Cc:

Description

The in_category function appears to fail for non-cached categories.

The code:

$categories = get_object_term_cache($post->ID, 'category');

if (false === $categories)
 $categories = wp_get_object_terms($post->ID, 'category');
if ( array_key_exists($category, $categories) )
 return true;
else
 return false;

Will produce erroneous results because the keys on the arrays returned from wp_get_object_terms() are numbered sequentially based on the number of results returned, and are NOT equal to the term_id field. IE:

get_object_term_cache() result:

Array
{
 [7] = object(term1, term_id = 7)
 [48] = object(term2, term_id = 48)
 [13] = object(term3, term_id = 13)
}

wp_get_object_terms result:

Array
{
 [0] = object(term1, term_id = 7)
 [1] = object(term2, term_id = 48)
 [2] = object(term3, term_id = 13)
}

Thus, If you were to call in_category(2) with a post in the above categories whose terms are not cached you'll get a false positive as array_key_exists(2, $the_above_array) will return true. Further, if you call in_category(48) with the same post you'll get a false negative as array_key_exists(48, $the_above_array) will return false.

Change History (1)

comment:1 @ryan7 years ago

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

(In [9289]) Fix in_category() when checking non-cached categories. fixes #7181

Note: See TracTickets for help on using tickets.