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);
}
Tagged in : #WordPress

Nilanchala

A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (goo.gl/qUZ0XV3), DZone MVB and founder of stacktips.com.

Join The Discussion

Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.