WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have three custom post types set up, articles, videos and photos.
I am using standard categories for these post types, and sharing the categories across all post types.

I am trying to create a nav menu for each post type, listing the categories, that should follow the following structure:

  • Photos

    • Cat 1
    • Cat 3
    • Cat 5
  • Videos

    • Cat 2
    • Cat 3
    • Cat 5
  • Articles

    • Cat 1
    • Cat 2
    • Cat 4

Categories that do not contain the custom post type should be hidden.

get_categories() with hide_empty set to 1 is obviously close, but it doesn't allow you to specify a post type.

share|improve this question
up vote 4 down vote accepted

Put the following in your functions.php:

function wp_list_categories_for_post_type($post_type, $args = '') {
    $exclude = array();

    // Check ALL categories for posts of given post type
    foreach (get_categories() as $category) {
        $posts = get_posts(array('post_type' => $post_type, 'category' => $category->cat_ID));

        // If no posts found, ...
        if (empty($posts))
            // ...add category to exclude list
            $exclude[] = $category->cat_ID;

    // Set up args
    if (! empty($exclude)) {
        $args .= ('' === $args) ? '' : '&';
        $args .= 'exclude='.implode(',', $exclude);

    // List categories

Now you can call wp_list_categories_for_post_type('photos'); or wp_list_categories_for_post_type('videos', 'order=DESC&title_li=Cats'); and the like.

share|improve this answer
Thanks t f. Exactly what I was looking for. It didn't quite work to start with, you forgot to filter get_posts with the category. – kdev Apr 19 '13 at 14:22
Oh, that's right. On my demo WP site, I only have a single category, that's why I didn't notice. Glad you found the bug, fixed it, and now it works. – tfrommen Apr 19 '13 at 14:30

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.