How to List Only Parent Categories in WordPress

WordPress provides default feature of category archives. We can also create sub-categories of the main category. While listing categories in sidebar via widget it displays all categories including every child category.

But what if we want to list only main categories with no other parent category?

Find Main or Only Parent Categories in WordPress

Here we are going to find out only categories with zero parents. We can also call it them Main categories.

In WordPress, we have get_categories() function to find the available categories and filter them according to our choice.

Here, we will filter categories with Zero parent to find out the main categories. In addition, get_categories() function provides orderby, order, hide_empty, and exclude parameters for more advanced listing solutions.

Read Also: Create New Widget in WordPress

Just copy and paste in the below code in your WP theme files where you want to list the categories and see the magic.

CODE

	$args = array(
		'orderby' => 'name',
		'order' => 'ASC',
		'parent'   => 0,
		'hide_empty' => 0,
		'exclude'   => '1'
		// we can also exclude parent categories from listing
	);

	$categories = get_categories( $args );
	echo "<ul>";
	for($i = 0; $i < count($categories); $i++){
		echo '<li><a href="'.get_site_url().'/'.$categories[$i]->slug.'/">'.$categories[$i]->name.'</a></li>';
	}
	echo "</ul>";
	}

Explanation

get_categories() function default outputs all the categories available. But it has some special parameters to filter categories according to our choice as given below.

  1. orderby – It shorts output categories according to Name, Id or any other valid parameter of category.
  2. order – It shorts the output categories either Ascending or Descending.
  3. Parent – It filters categories according to given parent id.
  4. hide_empty – It excludes categories with zero posts from the output.
  5. exclude – It excludes given categories from the output.

Conclusion

Categories are one of the most important and helpful features of WordPress structure. Even more, categories provide a high hand in SEO.

Enjoy WordPressing πŸ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *

Read previous post:
add a new widget wordpress
How to Create a New Custom Widget in WordPress

WordPress provides some default widgets to display extra content on the website. However, we can also create custom widgets when...

Close