How to Get Top Level Categories Taxonomy in WordPress

Home » Snippets » How to Get Top Level Categories Taxonomy in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

If you’re working with WordPress and need to retrieve the top-level categories for a specific taxonomy, you’ve come to the right place. Whether you’re building a custom navigation menu, creating a filter for your posts, or simply organizing your content, knowing how to access the top-level categories is essential. In this article, we’ll guide you through the steps of getting the top-level categories taxonomy in WordPress, so you can quickly and easily access the information you need.

					function wpturbo_get_top_level_categories_taxonomy() {
    $args = array(
        'taxonomy' => 'category',
        'parent' => 0,
        'hide_empty' => false,
    );

    $top_level_categories = get_categories($args);

    return $top_level_categories;
}
				

The code snippet provided is a function called wpturbo_get_top_level_categories_taxonomy(). This function is used to retrieve the top-level categories of the WordPress taxonomy "category". It returns an array of the top-level categories.

To achieve this, we pass an array of arguments to the get_categories() function to specify the criteria for the categories we want to retrieve. The arguments include:

  • taxonomy: This parameter specifies the taxonomy from which we want to retrieve the categories. In this case, we set it to ‘category’ to get the categories from the built-in WordPress category taxonomy.

  • parent: This parameter is set to 0 to get only the categories that have a parent of 0. Since we want the top-level categories, we set the parent to 0 to exclude any subcategories.

  • hide_empty: This parameter is set to false to retrieve even those categories that don’t have any posts assigned to them. By setting it to false, we ensure that empty categories are also included in the result.

After passing the arguments to get_categories(), we assign the returned categories to a variable called $top_level_categories. This variable will hold the array of top-level categories.

Finally, we return the $top_level_categories array so that it can be used elsewhere in our code.

By calling this function, you will get an array of the top-level categories in the ‘category’ taxonomy of your WordPress site.

Register an account to save your snippets or go Pro to get more features.