Custom Taxonomy Filter in WordPress Admin

If you have a lot of custom posts on your website, then sometimes it would be much easier to filter them by a specific taxonomy when you manage them in your WordPress admin.

Yes, search is also ok, but maybe a taxonomy filter will be just what you need? Here is how it is going to look like in WordPress admin:

custom taxonomy posts filter in WordPress admin
So here we have a CPT “Lessons” and a custom taxonomy “Courses” connected to it.

Below is the code that allows to add a taxonomy filter for a specific taxonomy:

<?php
add_action( 'restrict_manage_posts', 'rudr_taxonomy_filter' );

function rudr_taxonomy_filter( $post_type ) {

	// do nothing it it is not a post type we need
	if( 'lesson' !== $post_type ) {
		return;
	}
	
	$taxonomy_name = 'course_category';

	// get all terms of a specific taxonomy
	$courses = get_terms( 
		array( 
			'taxonomy' => $taxonomy_name, 
			'hide_empty' => false
		)
	);
	// selected taxonomy from URL
	$selected = isset( $_GET[ $taxonomy_name ] ) && $_GET[ $taxonomy_name ] ? $_GET[ $taxonomy_name ] : '';
	
	if( $courses ) {
		?>
			<select name="<?php echo $taxonomy_name ?>">
				<option value="">All courses</option>
				<?php
					foreach ( $courses as $course ) {
						?><option value="<?php echo $course->slug ?>"<?php selected( $selected, $course->slug ) ?>><?php echo $course->name ?></option><?php
					}
				?>
			</select>
		<?php
	}
}

What is worth to keep in mind here:

And also it is possible to simplify the filter by changing HTML to wp_dropdown_categories() and why not let’s extend it to multiple taxonomies.

add_action( 'restrict_manage_posts', 'rudr_taxonomy_filter' );

function rudr_taxonomy_filter( $post_type ){
	
	// let's decide about post type first
	if( 'my_post_type' !== $post_type ){
		return;
	}
	// pass multiple taxonomies as an array of their slugs
	$taxonomies = array( 'taxonomy_1', 'taxonomy_2' );
	
	// for every taxonomy we are going to do the same
	foreach( $taxonomies as $taxonomy ){
		
		$taxonomy_object = get_taxonomy( $taxonomy );
		$selected = isset( $_GET[ $taxonomy ] ) ? $_GET[ $taxonomy ] : '';
		
		wp_dropdown_categories( 
			array(
				'show_option_all' =>  $taxonomy_object->labels->all_items,
				'taxonomy'        =>  $taxonomy,
				'name'            =>  $taxonomy,
				'orderby'         =>  'name', // slug / count / term_order etc
				'value_field'     =>  'slug',
				'selected'        =>  $selected,
				'hierarchical'    =>  true,
			)
		);
	}
}
Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X