Restrict categories in wp drop down categories function

The function wp_dropdown_categories is used to display all categories as a drop down.

If a site uses different custom post types and if we want to show only categories used by a particular custom post type, we can use the following code. The following code displays categories used by the post type ‘highlight’.


$exclusive_post_type = 'highlights';
$exclude_cats = array();
$nonemptycats = get_terms( 'category' );
foreach( $nonemptycats as $term ){
$term_id = $term->term_id;
$term_objects = get_objects_in_term( $term_id, 'category' );
$exclude_term = true;

foreach( $term_objects as $post_id ){
if ( $exclusive_post_type === get_post_type( $post_id ) ){
$exclude_term = false;

break;
}
}
if ( $exclude_term ) $exclude_cats[] = $term_id;
}
$args = array(
'show_option_none' => 'All categories',
'orderby' => 'name',
'hide_empty' => 1,
'exclude' => $exclude_cats,
'hierarchical' => 1,
'hide_if_empty' => true
);
wp_dropdown_categories( $args );

Leave a Reply