Skip to content

Instantly share code, notes, and snippets.

@gavin310
Created February 3, 2022 06:40
Show Gist options
  • Save gavin310/833be65ec43a10abfe3b7df8aa739d1e to your computer and use it in GitHub Desktop.
Save gavin310/833be65ec43a10abfe3b7df8aa739d1e to your computer and use it in GitHub Desktop.
Output admin post listing taxonomy filter since wp_dropdown_categories is so limited
public static function add_admin_post_listing_taxonomy_filter( string $post_type, string $taxonomy_name, bool $select_current = false, bool $show_count = true, bool $hide_empty = true )
{
add_action( 'restrict_manage_posts', function( $cur_post_type ) use ( $post_type, $taxonomy_name, $select_current, $show_count, $hide_empty ) {
global $wpdb;
if ( $post_type !== $cur_post_type ) {
return;
}
$taxonomy = get_taxonomy( $taxonomy_name );
$filter_name = $taxonomy->query_var;
$filter_id = 'filter-by-' . $filter_name;
$filter_label = $taxonomy->labels->all_items;
$screen = get_current_screen();
if ( 'edit' === $screen->base ) {
$query_status = filter_input( INPUT_GET, 'post_status', FILTER_SANITIZE_STRING ) ?: '';
if ( in_array( $query_status, ['', 'all', 'trash'] ) ) {
$query_status = array( 'publish', 'future', 'draft', 'pending', 'private' );
}
$query_value = filter_input( INPUT_GET, $filter_name, FILTER_SANITIZE_STRING ) ?: '';
$template = '<select name="%s" id="%s">%s%s</select>';
$options = '';
$selected_value = '';
$terms = get_terms( array(
'pad_counts' => true,
'show_count' => false,
'hierarchical' => true,
'taxonomy' => $taxonomy->query_var,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
) );
foreach ( $terms as $term ) {
$post_ids = get_posts( array(
'post_type' => $post_type,
'post_status' => $query_status,
'numberposts' => -1,
'fields' => 'ids',
$filter_name => $term->slug,
) );
$count = count( $post_ids );
if ( $count > 0 || ! $hide_empty ) {
$option_selected = '';
if ( $select_current && $term->slug === $query_value ) {
$selected_value = $query_value;
$option_selected = ' selected';
}
$options .= sprintf( '<option value="%s"%s>%s%s</option>', esc_attr( $term->slug ), $option_selected, esc_html( $term->name ), $show_count ? "&nbsp;&nbsp;($count)" : '' );
}
}
$default_option = sprintf( '<option value=""%s>%s</option>', empty( $selected_value ) ? ' selected' : '', esc_html( $filter_label ) );
echo sprintf(
$template,
$filter_name,
$filter_id,
$default_option,
$options,
);
}
}, 99, 1 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment