Get All Categories In WordPress
There are times when you want to get a list of all the categories of your WordPress site, this is commonly found on a archive page. But I've recently created a mobile version of a site where a dropdown box was needed with a list of all the categories on the site.
With WordPress this is very easy to do you can just use one of the built in functions to get all the categories for the site. The WordPress function we can use is get_categories().
$categories = get_categories( $args );
This will return an array of category objects where you can loop through and get all the information you need.
You can pass in one parameter to this function which you can use to narrow down which categories are returned. Here is a list of arguments you can send to the get_categories() function.
<?php $args = array( 'type' => 'post', 'child_of' => 0, 'parent' => '', 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => 1, 'hierarchical' => 1, 'exclude' => '', 'include' => '', 'number' => '', 'taxonomy' => 'category', 'pad_counts' => false );?>
Create A Dropdown Box Of Categories
The get_categories() function wasn't the function that I used to create a dropdown on the mobile site. WordPress has another built in function to create a dropdowns populated with all the categories of the site. This function is wp_dropdown_categories().
<?php wp_dropdown_categories( $args ); ?>
This function takes one parameter which is a set of arguments to narrow down which categories are displayed. If you want to display all categories just leave this argument blank.
The other arguments used in this function are:
<?php $args = array( 'show_option_all' => '', 'show_option_none' => '', 'orderby' => 'ID', 'order' => 'ASC', 'show_count' => 0, 'hide_empty' => 1, 'child_of' => 0, 'exclude' => '', 'echo' => 1, 'selected' => 0, 'hierarchical' => 0, 'name' => 'cat', 'id' => '', 'class' => 'postform', 'depth' => 0, 'tab_index' => 0, 'taxonomy' => 'category', 'hide_if_empty' => false ); ?>
To create a dropdown populated with only categories which have posts assigned to them use the following code snippet.
<?php wp_dropdown_categories(array('hide_empty' => 1)); ?>
Learn how to code with Treehouse
- Learn projects with access to 1000+ videos
- Practice live with our Code Challenge Engine
- Get help in our members-only forums
Join the weekly newsletter
Sign up for our newsletter. You'll be updated on new tutorials as they come available.
Subscribe today and get a 50% discount code to Paulund