2017-01-10 264 views
1

我试图过滤'所有职位'的管理员屏幕,以检索具有独特类别的职位。 到现在为止,我已经设法设置与prase_query挂钩的URL $ _GET键:WordPress的管理员更改查询

add_filter('parse_query', 'lxa_admin_posts_filter'); 
    function lxa_admin_posts_filter($query) { 
    global $pagenow; 
     if (is_admin() && $pagenow=='edit.php' && isset($_GET['category_only']) && $_GET['category_only'] != '') { 
     $query->query_vars['meta_key'] = $_GET['category_only']; 
    } 
} 

后来,使用restrict_manage_posts钩,我已经创建了一个包含所有我的文章的类别下拉:

function lxa_admin_posts_filter_restrict_manage_posts() { 
global $wpdb; 

$categories = get_categories(array(
    'taxonomy' => 'category', 
    'orderby' => 'name', 
    'parent' => 0, 
    'hierarchical' => true, 
)); 

?> 
<select name="category_only"> 
<option value=""><?php _e('Filter By Category Only', 'baapf'); ?></option> 
<?php foreach ($categories as $category) { 
    echo '<option value= "' . $category -> term_id . '" > ' . $category -> name . '</option>'; 

} 

?> 
</select> 


<?php } 

有可能使用这个'category_only'键来改变循环,以检索只有一个类别的文章?

谢谢

回答

1

我建议使用此代码:

/** 
* Display a custom taxonomy dropdown in admin 
* @author Mike Hemberger 
* @link http://thestizmedia.com/custom-post-type-filter-admin-custom-taxonomy/ 
*/ 
add_action('restrict_manage_posts', 'tsm_filter_post_type_by_taxonomy'); 
function tsm_filter_post_type_by_taxonomy() { 
    global $typenow; 
    $post_type = 'lessons_cpt'; // change to your post type 
    $taxonomy = 'chapters'; // change to your taxonomy 
    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'  => true, 
     )); 
    }; 
} 
/** 
* Filter posts by taxonomy in admin 
* @author Mike Hemberger 
* @link http://thestizmedia.com/custom-post-type-filter-admin-custom-taxonomy/ 
*/ 
add_filter('parse_query', 'tsm_convert_id_to_term_in_query_videos'); 
function tsm_convert_id_to_term_in_query_videos($query) { 
    global $pagenow; 
    $post_type = 'lessons_cpt'; // change to your post type 
    $taxonomy = 'chapters'; // change to your taxonomy 
    $q_vars = &$query->query_vars; 
    if ($pagenow == 'edit.php' && isset($q_vars['post_type']) && $q_vars['post_type'] == $post_type && isset($q_vars[$taxonomy]) && is_numeric($q_vars[$taxonomy]) && $q_vars[$taxonomy] != 0) { 

    $term = get_term_by('id', $q_vars[$taxonomy], $taxonomy); 
     $q_vars[$taxonomy] = $term->slug; 
    } 
} 

你只需要改变CPT和分类。 我在最近的一个项目中使用过,效果很好。

来源: http://thestizmedia.com/custom-post-type-filter-admin-custom-taxonomy/

+1

工作就像一个魅力。必须做一些调整来处理我现有的代码 – Adrian