Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save koskinenaa/5baa7df3235dfa6f2da3896a25cc687f to your computer and use it in GitHub Desktop.
Save koskinenaa/5baa7df3235dfa6f2da3896a25cc687f to your computer and use it in GitHub Desktop.
Add taxonomy to a WordPress post type as a filter. See https://gist.github.com/koskinenaa/86fd3acd75959e9aa0635ce00934e26c for multiple post types and taxonomies
public function filter_post_type_by_taxonomy( $post_type, $which ) {
if ( 'my_post_type' == $post_type ) {
$taxonomy = get_taxonomy( 'my_taxonomy' );
if ( $taxonomy ) {
// Retrieve taxonomy terms
$terms = get_terms( $taxonomy->name );
// Display filter HTML
echo "<select name='{$taxonomy->name}' id='{$taxonomy->name}' class='postform'>";
echo '<option value="">' . sprintf( esc_html__( 'Show All %s', 'text-domain' ), $taxonomy->labels->name ) . '</option>';
foreach ( $terms as $term ) {
printf(
'<option value="%1$s" %2$s>%3$s (%4$s)</option>',
$term->slug,
( ( isset( $_GET[$taxonomy->name] ) && ( $_GET[$taxonomy->name] == $term->slug ) ) ? ' selected="selected"' : '' ),
$term->name,
$term->count
);
}
echo '</select>';
}
}
}
}
add_action( 'restrict_manage_posts', 'filter_post_type_by_taxonomy' , 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment