Skip to content

Instantly share code, notes, and snippets.

@richjenks
Created December 15, 2016 16:59
Show Gist options
  • Save richjenks/ab9150bd00befba47d4944bec619c9c1 to your computer and use it in GitHub Desktop.
Save richjenks/ab9150bd00befba47d4944bec619c9c1 to your computer and use it in GitHub Desktop.
Adds filter for taxonomies to posts table
<?php
/**
* Adds filter for taxonomies to posts table
*
* Adapted from:
* @see http://wordpress.org/support/topic/custom-taxonomy-filter-not-working-in-admin-editphp-31b2?replies=8#post-2400615
* @see https://wordpress.stackexchange.com/questions/578/adding-a-taxonomy-filter-to-admin-list-for-a-custom-post-type/3215#3215
*
* @param array $taxonomy Filter to be added
* @param string $post_type Post type to get filter
*/
function add_taxonomy_filter( $taxonomy, $post_type ) {
add_action( 'restrict_manage_posts', function() use ( $taxonomy, $post_type ) {
if ( $GLOBALS['typenow'] == $post_type ) {
$tax_obj = get_taxonomy( $taxonomy );
$tax_name = $tax_obj->labels->name;
$terms = get_terms( $taxonomy );
$name = ( $taxonomy === 'post_tag' ) ? 'tag' : $taxonomy;
echo "<select name='$name' id='$taxonomy' class='postform'>";
echo "<option value=''>All $tax_name</option>";
if ( !isset( $_GET[$taxonomy] ) ) $_GET[ $taxonomy ] = $taxonomy;
foreach ( $terms as $term ) {
echo '<option value='. $term->slug, $_GET[ $name ] == $term->slug ? ' selected="selected"' : '','>' . $term->name .' (' . $term->count .')</option>';
}
echo "</select>";
}
} );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment