WordPress 技巧:后台文章列表添加自定义分类筛选
如果你的文章或者文章类型添加了自定义分类,下面的代码可以在 WordPress 后台文章列表添加自定义分类下拉筛选框,快速通过自定义分类筛选文章。
add_action('restrict_manage_posts', function($post_type){
if($taxonomies = get_object_taxonomies($post_type, 'objects')){
foreach($taxonomies as $taxonomy) {
if(empty($taxonomy->hierarchical) || empty($taxonomy->show_admin_column)){
continue;
}
if($taxonomy->name == 'category'){
$taxonomy_key = 'cat';
}else{
$taxonomy_key = $taxonomy->name.'_id';
}
$selected = 0;
if(!empty($_REQUEST[$taxonomy_key])){
$selected = $_REQUEST[$taxonomy_key];
}elseif(!empty($_REQUEST['taxonomy']) && ($_REQUEST['taxonomy'] == $taxonomy->name) && !empty($_REQUEST['term'])){
if($term = get_term_by('slug', $_REQUEST['term'], $taxonomy->name)){
$selected = $term->term_id;
}
}elseif(!empty($taxonomy->query_var) && !empty($_REQUEST[$taxonomy->query_var])){
if($term = get_term_by('slug', $_REQUEST[$taxonomy->query_var], $taxonomy->name)){
$selected = $term->term_id;
}
}
wp_dropdown_categories(array(
'taxonomy' => $taxonomy->name,
'show_option_all' => $taxonomy->labels->all_items,
'show_option_none' => '没有设置',
'hide_if_empty' => true,
'hide_empty' => 0,
'hierarchical' => 1,
'show_count' => 0,
'orderby' => 'name',
'name' => $taxonomy_key,
'selected' => $selected
));
}
}
});
该功能已经整合到 WPJAM Basic 插件中,并已免费提供下载,简单勾选或者设置下即可开启!