get_category_parents()
Gets a list of parent categories of the current category. The list is displayed in hierarchical order.
You can specify that the names of the parent categories are links to the categories themselves (something like breadcrumbs).
Since version 4.8, the function has become a wrapper for get_term_parents_list(). The 4th parameter has been deprecated.
No Hooks.
Returns
String|WP_Error
. HTML code, a list of parent categories. Or a WP_Error object.
Usage
$cat_parents = get_category_parents( $id, $link, $separator, $nicename );
- $id(integer) (required)
- ID of the category for which to display parent categories.
- $link(boolean)
- true - will display the list of parent categories as links to category pages.
false - will display the names.
Default: false - $separator(string)
- Separator between names.
Default: '/' - $nicename(boolean)
- true - will display alternative names (slugs) of categories (which are used in URLs)
false - will display real names.
Default: false
Examples
#1 Derive the parent categories of category 10
In the form of links separated by »
. The link to category 10 will also be displayed.
<?php echo get_category_parents( 10, true, ' » '); ?>
will output:
Internet » Blogging » WordPress »
#2 Get the top parent element for the nested element
We need to get the first (root) parent element (term) of the taxonomy to the current element. That is, we have a taxonomy element, and we need to get the topmost element of that term in the hierarchy.
See this example: https://wp-kama.com/function/get_the_terms#example_257
See the answer in the question: How do I get the top-level taxonomy element in which the specified post (post) is located?
Changelog
Since 1.2.0 | Introduced. |
Since 4.8.0 | The $visited parameter was deprecated and renamed to $deprecated. |
get_category_parents() get category parents code WP 6.8.1
function get_category_parents( $category_id, $link = false, $separator = '/', $nicename = false, $deprecated = array() ) { if ( ! empty( $deprecated ) ) { _deprecated_argument( __FUNCTION__, '4.8.0' ); } $format = $nicename ? 'slug' : 'name'; $args = array( 'separator' => $separator, 'link' => $link, 'format' => $format, ); return get_term_parents_list( $category_id, 'category', $args ); }