How to List Only Parent Categories in WordPress

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

But what if we want to list only the 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 the get_categories() function to find the available categories and filter them according to our choice.

Here, we will filter categories with Zero parents to determine the main categories. The 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 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 the 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 *