2017-01-10 262 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