Aleš Sýkora / April 7, 2022 / 0 comments
Get all child terms of parent taxonomy term in WordPress
2 min read / Custom Code, WordPress / Share on: Twitter, LinkedIn, Facebook
Post summary: I have my taxonomy with multiple levels. Here is an example: ProductsJackpotsSlotsTablesCompanyleadershipnewsalerts Sometimes, you want to display only child terms of parent taxonomy. In this case, I need to display all child terms of products term. What do I need to prepare? I need taxonomy ID from WordPress admin, and prepare a query. Here is…
I have my taxonomy with multiple levels. Here is an example:
- Products
- Jackpots
- Slots
- Tables
- Company
- leadership
- news
- alerts
Sometimes, you want to display only child terms of parent taxonomy. In this case, I need to display all child terms of products term. What do I need to prepare? I need taxonomy ID from WordPress admin, and prepare a query.
Here is the list of avaialble query args:
$defaults = array(
'child_of' => 0,
'current_category' => 0,
'depth' => 0,
'echo' => 1,
'exclude' => '',
'exclude_tree' => '',
'feed' => '',
'feed_image' => '',
'feed_type' => '',
'hide_empty' => 1,
'hide_title_if_empty' => false,
'hierarchical' => true,
'order' => 'ASC',
'orderby' => 'name',
'separator' => '<br />',
'show_count' => 0,
'show_option_all' => '',
'show_option_none' => __( 'No categories' ),
'style' => 'list',
'taxonomy' => 'category',
'title_li' => __( 'Categories' ),
'use_desc_for_title' => 1,
);
If you need to know more, follow official WordPress documentation: wp_list_categories() | Function | WordPress Developer Resources.
So in case you need only child terms, you need to use query like this:
<?php
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC',
'child_of' => 11, //set your category ID
'hide_empty' => 0,
'hide_title_if_empty' => false,
'order' => 'ASC',
'orderby' => 'name',
) );
foreach( $categories as $category ) {
echo '<a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a>';
}
?>
You can also use the wp_list_categories() function, but I prefer get_categories for more customizable output.
Fuel my passion for writing with a beer🍺
Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻