Created
July 31, 2019 16:09
-
-
Save iamandrewpeters/d45e4a47c8f9740f7c6537e5fadffb9f to your computer and use it in GitHub Desktop.
Add Filter to Media with a Taxonomy
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
// register new taxonomy which applies to attachments | |
function reach_add_media_taxonomy() { | |
$labels = array( | |
'name' => 'Media Type', | |
'singular_name' => 'Media Type', | |
'search_items' => 'Search Media Types', | |
'all_items' => 'All Media Types', | |
'parent_item' => 'Parent Media Type', | |
'parent_item_colon' => 'Parent Media Type:', | |
'edit_item' => 'Edit Media Type', | |
'update_item' => 'Update Media Type', | |
'add_new_item' => 'Add New Media Type', | |
'new_item_name' => 'New Media Type Name', | |
'menu_name' => 'Media Type', | |
); | |
$args = array( | |
'labels' => $labels, | |
'hierarchical' => true, | |
'public' => true, | |
'show_ui' => true, | |
'show_admin_column' => true, | |
'show_in_nav_menus' => true, | |
'show_tagcloud' => false, | |
'show_in_rest' => true, | |
); | |
register_taxonomy( 'media_type', 'attachment', $args ); | |
} | |
add_action( 'init', 'reach_add_media_taxonomy' ); | |
// Display a custom taxonomy dropdown in admin: | |
if ( ! function_exists('andrews_filter_post_type_by_taxonomy') ) { | |
function andrews_filter_post_type_by_taxonomy() { | |
global $typenow; | |
$post_type = '{attachment}'; | |
$taxonomy = '{media_type}'; | |
if ($typenow == $post_type) { | |
$selected = isset($_GET[$taxonomy]) ? $_GET[$taxonomy] : ''; | |
$info_taxonomy = get_taxonomy($taxonomy); | |
wp_dropdown_categories(array( | |
'show_option_all' => __("Show All {$info_taxonomy->label}"), | |
'taxonomy' => $taxonomy, | |
'name' => $taxonomy, | |
'orderby' => 'name', | |
'selected' => $selected, | |
'show_count' => true, | |
'hide_empty' => false, | |
// 'hierarchical' => 1, | |
'value_field' => 'slug', | |
)); | |
}; | |
} | |
add_action('restrict_manage_posts', 'andrews_filter_post_type_by_taxonomy'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a slightly different method, possibly more efficient as it doesn't use the global variable