Last active
August 19, 2020 20:08
-
-
Save petenelson/0bd45b151c7a266a180ff11034c43135 to your computer and use it in GitHub Desktop.
WordPress: Taxonomy dropdown for admin list filter
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
/** | |
* Outputs a taxonomy dropdown list. | |
* | |
* @param string $taxonomy The taxonomy name | |
* @param array $args Additional args. | |
* @return void | |
*/ | |
function taxonomy_dropdown( $taxonomy, $args = [] ) { | |
if ( ! taxonomy_exists( $taxonomy ) ) { | |
return; | |
} | |
$taxonomy = get_taxonomy( $taxonomy ); | |
$args = wp_parse_args( | |
$args, | |
[ | |
'all_items_label' => $taxonomy->labels->all_items, | |
'selected_term' => filter_input( INPUT_GET, $taxonomy->name, FILTER_SANITIZE_STRING ), | |
'terms' => get_terms( $taxonomy->name, array( 'hide_empty' => true ) ), | |
'name' => $taxonomy->name, | |
'id' => 'dropdown-' . $taxonomy->name, | |
] | |
); | |
$args = apply_filters( __FUNCTION__, $args, $taxonomy ); | |
?> | |
<select name="<?php echo esc_attr( $args['name'] ); ?>" id="<?php echo esc_attr( $args['id'] ); ?>"> | |
<option value=""><?php echo esc_html( $args['all_items_label'] ); ?> | |
<?php foreach( $args['terms'] as $term ) : ?> | |
<option value="<?php echo esc_attr( $term->slug ); ?>" <?php selected( $term->slug, $args['selected_term'] ); ?>><?php echo esc_html( $term->name ); ?></option> | |
<?php endforeach; ?> | |
</select> | |
<?php | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment