Skip to content

Instantly share code, notes, and snippets.

@jtsternberg
Created December 14, 2013 23:55
Show Gist options
  • Save jtsternberg/7966682 to your computer and use it in GitHub Desktop.
Save jtsternberg/7966682 to your computer and use it in GitHub Desktop.
Filtering multiple taxonomies in admin post listing pages
<?php
add_action( 'restrict_manage_posts', 'add_admin_taxonomy_filters' );
/**
* Filtering for 2 taxonomies, 'genres', and 'colors'
*/
function add_admin_taxonomy_filters() {
$screen = get_current_screen();
if ( ! isset( $screen->id ) || $screen->id !== 'edit-post' )
return;
foreach ( array( 'genres', 'colors' ) as $taxonomy ) {
build_taxonomy_dropdown( $taxonomy );
}
}
/**
* Create a select dropdown for a taxonomy
*/
function build_taxonomy_dropdown( $taxonomy ) {
$taxonomy_object = get_taxonomy( $taxonomy );
$args = array(
'orderby' => 'name',
'hide_empty' => 0,
);
$terms = get_terms( $taxonomy, $args );
$selected = isset( $_REQUEST[ $taxonomy ] ) ? esc_attr( $_REQUEST[ $taxonomy ] ) : 0;
$output = '<select name="'. $taxonomy .'" id="'. $taxonomy .'-dropdown" class="postform">';
if ( empty( $terms ) ) {
$output .= '<option value="-1" selected="selected">'. sprintf( __( 'No %s' ), $taxonomy_object->label ) .'</option>';
} else {
$output .= '<option value="0" '. selected( $selected, 0, false ) .'>'. sprintf( __( 'View All %s' ), $taxonomy_object->label ) .'</option>';
foreach ( $terms as $term ) {
$output .= '<option value="'. $term->slug .'" '. selected( $selected, $term->slug, false ) .'>'. $term->name .'</option>';
}
}
$output .= '</select>';
echo $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment