get_category_parents

Retrieve category parents with separator.

Description

(string|WP_Error) get_category_parents( (int) $id, (constant) $link = false, (string) $separator = '/', (constant) $nicename = false, (array) $visited = array() ); 

Returns (string|WP_Error)

A list of category parents on success, WP_Error on failure.

Parameters (5)

0. $id (int)
Category ID.
1. $link — Optional. (constant) => false
Optional, default is false. Whether to format with link.
2. $separator — Optional. (string) => '/'
Optional, default is /.. How to separate categories.
3. $nicename — Optional. (constant) => false
Optional, default is false. Whether to use nice name for display.
4. $visited — Optional. (array) => array()
Already linked to categories to prevent duplicates.

Usage

  1. if ( !function_exists( 'get_category_parents' ) ) { 
  2. require_once ABSPATH . WPINC . '/category-template.php'; 
  3.  
  4. // Category ID. 
  5. $id = -1; 
  6.  
  7. // Optional, default is false. Whether to format with link. 
  8. $link = false; 
  9.  
  10. // Optional, default is '/'. How to separate categories. 
  11. $separator = '/'; 
  12.  
  13. // Optional, default is false. Whether to use nice name for display. 
  14. $nicename = false; 
  15.  
  16. // Optional. Already linked to categories to prevent duplicates. 
  17. $visited = array(); 
  18.  
  19. // NOTICE! Understand what this does before running. 
  20. $result = get_category_parents($id, $link, $separator, $nicename, $visited); 
  21.  

Defined (1)

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

/wp-includes/category-template.php  
  1. function get_category_parents( $id, $link = false, $separator = '/', $nicename = false, $visited = array() ) { 
  2. $chain = ''; 
  3. $parent = get_term( $id, 'category' ); 
  4. if ( is_wp_error( $parent ) ) 
  5. return $parent; 
  6.  
  7. if ( $nicename ) 
  8. $name = $parent->slug; 
  9. else 
  10. $name = $parent->name; 
  11.  
  12. if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) { 
  13. $visited[] = $parent->parent; 
  14. $chain .= get_category_parents( $parent->parent, $link, $separator, $nicename, $visited ); 
  15.  
  16. if ( $link ) 
  17. $chain .= '<a href="' . esc_url( get_category_link( $parent->term_id ) ) . '">'.$name.'</a>' . $separator; 
  18. else 
  19. $chain .= $name.$separator; 
  20. return $chain;