您可以使用pre_get_posts
筛选查询。
所以你可以
从查询变量中检索类别检索具有该类别的帖子将媒体查询设置为仅包括以该帖子为父级的帖子,以提供您可以使用的UIrestrict_manage_posts
挂钩以输出类别下拉列表。
add_action(\'pre_get_posts\', \'my_filter_media_by_cat\');
add_action( \'restrict_manage_posts\', \'my_add_media_cat_dropdown\' );
function my_filter_media_by_cat( $q ) {
$scr = get_current_screen();
$cat = filter_input(INPUT_GET, \'postcat\', FILTER_SANITIZE_STRING );
if ( ! $q->is_main_query() || ! is_admin() || (int)$cat <= 0 || $scr->base !== \'upload\' )
return;
// get the posts
$posts = get_posts( \'nopaging=1&category=\' . $cat );
// get post ids
$pids = ( ! empty( $posts ) ) ? wp_list_pluck($posts, \'ID\') : false;
if ( ! empty($pids) ) {
$pidstxt = implode($pids, \',\');
global $wpdb;
// get the ids of media having retrieved posts as parent
$mids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_parent IN ($pidstxt)");
if ( ! empty($mids) ) {
// force media query to retrieve only media having retrieved posts as parent
$q->set( \'post__in\', $mids );
} else {
// force media query to return no posts
$q->set( \'p\', -1 ); // let query found nothing
}
}
}
function my_add_media_cat_dropdown() {
$scr = get_current_screen();
if ( $scr->base !== \'upload\' ) return;
$cat = filter_input(INPUT_GET, \'postcat\', FILTER_SANITIZE_STRING );
$selected = (int)$cat > 0 ? $cat : \'-1\';
$args = array(
\'show_option_none\' => \'All Post Categories\',
\'name\' => \'postcat\',
\'selected\' => $selected
);
wp_dropdown_categories( $args );
}
这段代码的缺点是你必须运行3个查询来过滤媒体。。。
UI上的结果: