Last active
June 6, 2020 21:36
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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