The get_category_children() WordPress PHP function retrieves a list of category children separated before and after the term IDs.
Usage
get_category_children($id, $before = '/', $after = '', $visited = array());
Parameters
$id
(int) – Category ID to retrieve children.$before
(string) – Optional. Prepend before category term ID. Default ‘/’.$after
(string) – Optional. Append after category term ID. Default: ”.$visited
(array) – Optional. Category Term IDs that have already been added. Default: array().
More information
See WordPress Developer Resources: get_category_children()
Important: This function is deprecated. To replace it with get_term_children()
, note that get_category_children()
returns a string, while get_term_children()
returns an array of Category IDs. Also, get_term_children()
requires a second parameter of ‘category’, which is the name of the pre-defined Taxonomy for Categories.
Examples
Display child categories for a specific category
// Get child categories of the category with ID 5 $child_categories = get_category_children(5); echo $child_categories;
Custom separators for child categories
// Get child categories of the category with ID 6 and custom separators $child_categories = get_category_children(6, '(', ')'); echo $child_categories;
Using get_category_children() in a loop
// Get all top-level categories $categories = get_categories(array('parent' => 0)); // Loop through categories and display their child categories foreach ($categories as $category) { $child_categories = get_category_children($category->term_id); echo $category->name . ': ' . $child_categories; }
Avoid duplicates with the $visited parameter
// Get child categories of the category with ID 7 and avoid duplicates $visited = array(12, 15); // Category IDs to exclude $child_categories = get_category_children(7, '/', '', $visited); echo $child_categories;
Create a nested list of categories and their children
function display_category_children($parent_id) { // Get child categories of the given parent ID $child_categories = get_categories(array('parent' => $parent_id)); // Display child categories in a nested list if (!empty($child_categories)) { echo '<ul>'; foreach ($child_categories as $child_category) { echo '<li>' . $child_category->name; display_category_children($child_category->term_id); echo '</li>'; } echo '</ul>'; } } // Display a nested list of categories and their children for the category with ID 8 display_category_children(8);