_pad_term_counts

Add count of children to parent count.

Description

_pad_term_counts( (array) &$terms, (string) $taxonomy ); 

Recalculates term counts by including items from child terms. Assumes all relevant children are already in the $terms argument.

Parameters (2)

0. $terms (array) => &$terms
List of term objects, passed by reference.
1. $taxonomy (string)
The taxonomy.

Usage

  1. if ( !function_exists( '_pad_term_counts' ) ) { 
  2. require_once ABSPATH . WPINC . '/taxonomy.php'; 
  3.  
  4. // List of term objects, passed by reference. 
  5. $terms = array(); 
  6.  
  7. // The taxonomy. 
  8. $taxonomy = ''; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = _pad_term_counts($terms, $taxonomy); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/taxonomy.php  
  1. function _pad_term_counts( &$terms, $taxonomy ) { 
  2. global $wpdb; 
  3.  
  4. // This function only works for hierarchical taxonomies like post categories. 
  5. if ( !is_taxonomy_hierarchical( $taxonomy ) ) 
  6. return; 
  7.  
  8. $term_hier = _get_term_hierarchy($taxonomy); 
  9.  
  10. if ( empty($term_hier) ) 
  11. return; 
  12.  
  13. $term_items = array(); 
  14. $terms_by_id = array(); 
  15. $term_ids = array(); 
  16.  
  17. foreach ( (array) $terms as $key => $term ) { 
  18. $terms_by_id[$term->term_id] = & $terms[$key]; 
  19. $term_ids[$term->term_taxonomy_id] = $term->term_id; 
  20.  
  21. // Get the object and term ids and stick them in a lookup table. 
  22. $tax_obj = get_taxonomy($taxonomy); 
  23. $object_types = esc_sql($tax_obj->object_type); 
  24. $results = $wpdb->get_results("SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships INNER JOIN $wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (" . implode(', ', array_keys($term_ids)) . ") AND post_type IN ('" . implode("', '", $object_types) . "') AND post_status = 'publish'"); 
  25. foreach ( $results as $row ) { 
  26. $id = $term_ids[$row->term_taxonomy_id]; 
  27. $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1; 
  28.  
  29. // Touch every ancestor's lookup row for each post in each term. 
  30. foreach ( $term_ids as $term_id ) { 
  31. $child = $term_id; 
  32. $ancestors = array(); 
  33. while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) { 
  34. $ancestors[] = $child; 
  35. if ( !empty( $term_items[$term_id] ) ) 
  36. foreach ( $term_items[$term_id] as $item_id => $touches ) { 
  37. $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1; 
  38. $child = $parent; 
  39.  
  40. if ( in_array( $parent, $ancestors ) ) { 
  41. break; 
  42.  
  43. // Transfer the touched cells. 
  44. foreach ( (array) $term_items as $id => $items ) 
  45. if ( isset($terms_by_id[$id]) ) 
  46. $terms_by_id[$id]->count = count($items);