Don't like ads? PRO users don't see any ads ;-)
Guest

Restrict category drop down to a specific post type

By: tcbarrett on Jan 19th, 2012  |  syntax: PHP  |  size: 0.89 KB  |  hits: 108  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1.    <?php
  2.     $exclusive_post_type = 'book';
  3.     $exclude_cats        = array();
  4.     $nonemptycats        = get_terms( 'category' );
  5.     foreach( $nonemptycats as $term ){
  6.       $term_id                 = $term->term_id;
  7.       $term_objects            = get_objects_in_term( $term_id, 'category' );
  8.       $exclude_term            = true;
  9.       foreach( $term_objects as $post_id ){
  10.         if ( $exclusive_post_type === get_post_type( $post_id ) ){
  11.           $exclude_term = false;
  12.           break;
  13.         }
  14.       }
  15.       if ( $exclude_term ) $exclude_cats[] = $term_id;
  16.     }
  17.  
  18.     $args = array(
  19.       'orderby'         => 'name',
  20.       'show_count'      => false,
  21.       'hide_if_empty'   => true,
  22.       'show_option_all' => 'All categories',
  23.       'depth'           => 1,
  24.       'exclude'         => $exclude_cats,
  25.     );
  26.   ?>
  27.   Categories: <?php wp_dropdown_categories( $args ); ?>