Skip to content

Instantly share code, notes, and snippets.

@donini
Last active September 7, 2019 20:57
Show Gist options
  • Save donini/5e896bf17fb3bef9d9e4c48d4ed3248d to your computer and use it in GitHub Desktop.
Save donini/5e896bf17fb3bef9d9e4c48d4ed3248d to your computer and use it in GitHub Desktop.
7-add-new-taxonomy-filter.php
<?php
add_action( 'restrict_manage_posts', 'filter_posts_by_topics', 10, 2 );
function filter_posts_by_topics( $post_type, $which ) {
/* Apply this only on a specific post type */
if ( 'post' !== $post_type ) {
return;
}
/* A list of taxonomy slugs to filter by */
$taxonomies = array( 'topics' );
foreach ( $taxonomies as $taxonomy_slug ) {
$taxonomy_obj = get_taxonomy( $taxonomy_slug ); /* Retrieve taxonomy data */
$taxonomy_name = $taxonomy_obj->labels->name;
$terms = get_terms( array(
'taxonomy' => 'topics',
'hide_empty' => false,
) ); /* Retrieve taxonomy terms */
/* Display filter HTML */
echo '<select name="{$taxonomy_slug}" id="{$taxonomy_slug}" class="postform">';
echo '<option value="">' . sprintf( esc_attr__( 'Show All %s', 'text_domain' ), esc_attr( $taxonomy_name ) ) . '</option>';
foreach ( $terms as $term ) {
printf(
'<option value="%1$s" %2$s>%3$s (%4$s)</option>',
esc_attr( $term->slug ),
( ( isset( $_GET[$taxonomy_slug] ) && ( $_GET[$taxonomy_slug] === $term->slug ) ) ? ' selected="selected"' : '' ),
esc_attr( $term->name ),
esc_attr( $term->count )
);
}
echo '</select>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment