Paulund
2012-05-02 #wordpress

Display Categories Of A Custom Post Type

When you are using custom post types they some people get confused to how they function, some people think they are different than normal posts. But the main thing you have to remember is that they are exactly the same as the normal posts you get in WordPress. The only difference is there isn't any in-built WordPress functions to get the information you need, but you can get it by using the wp_query class. This offers a nice way to access all the information in your WordPress database. There are lots of other methods you can use to get data from the database in this tutorial we are going to look at getting the list of categories in WordPress for your posts.

WordPress List Of Categories

To get a list of all the categories in WordPress it's quite simple all you have to do is using the function wp_list_categories().


<?php wp_list_categories( $args ); ?> 

The default arguments passed to this are:


<?php $args = array(
    'show_option_all'    => ,
    'orderby'            => 'name',
    'order'              => 'ASC',
    'style'              => 'list',
    'show_count'         => 0,
    'hide_empty'         => 1,
    'use_desc_for_title' => 1,
    'child_of'           => 0,
    'feed'               => ,
    'feed_type'          => ,
    'feed_image'         => ,
    'exclude'            => ,
    'exclude_tree'       => ,
    'include'            => ,
    'hierarchical'       => true,
    'title_li'           => __( 'Categories' ),
    'show_option_none'   => __('No categories'),
    'number'             => NULL,
    'echo'               => 1,
    'depth'              => 0,
    'current_category'   => 0,
    'pad_counts'         => 0,
    'taxonomy'           => 'category',
    'walker'             => 'Walker_Category' ); ?>

This will display a list of categories as links. ## List Custom Post Types Categories

The above function will return all the categories for the normal post types but it will not return the categories for your custom post types. To get the custom post type categories you need to change the arguments passed into the wp_list_categories function. You need to define the taxonomy argument. If you have a custom post type for your products then to display all the categories for products you need to use the following snippet.


$customPostTaxonomies = get_object_taxonomies('products');

if(count($customPostTaxonomies) > 0)
{
     foreach($customPostTaxonomies as $tax)
     {
	     $args = array(
         	  'orderby' => 'name',
	          'show_count' => 0,
        	  'pad_counts' => 0,
	          'hierarchical' => 1,
        	  'taxonomy' => $tax,
        	  'title_li' => ''
        	);

	     wp_list_categories( $args );
     }
}