How to Fetch All Sub Categories of an Selected WordPress Category
The following code snippet will fetch all sub categories of selected category. Add the following code snippet to your themes archive.php/category.php page.
<section class="sub-category"> <div class="container"> <?php $cur_cat = get_query_var('cat'); $args=array( 'child_of' => $cur_cat, 'hide_empty' => 0, 'orderby' => 'name', 'order' => 'ASC', 'depth' => '1' ); $categories=get_categories($args); foreach($categories as $category) { echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'; } ?> <div> </section>
Let us add some styling to it.
section.sub-category { background: #ECF1F7; } .sub-category a { background: #1B9CE2; padding: 3px 10px; color: #fff; display: inline-block; font-size: 14px; text-transform: uppercase; font-weight: bold; margin: 10px; margin-right: 5px; border-radius: 3px; -webkit-transition: all .3s ease; } .sub-category a:hover { text-decoration: none; background: rgba(25, 128, 183, 0.79); }
Sharing is caring!
Did you like what Editorial wrote? Thank them for their work by sharing it on social media.