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?
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.
Categories are one of the most important and helpful features of WordPress structure. Even more, categories provide a high hand in SEO.
Enjoy WordPressing 🙂
There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…
In this tutorial, I'm going to show you how to install MySQL on your computer.…
Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…
We can redirect any webpage to any other or redirect the whole domain or website…
There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…
Include files in PHP are used in appending various global or config files. We can…