Advertisement
miriamdepaula

WordPress: Adding a Taxonomy Filter to Admin List for a CPT

Apr 23rd, 2012
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.68 KB | None | 0 0
  1. // Adding a Taxonomy Filter to Admin List for a Custom Post Type
  2. add_action( 'restrict_manage_posts', 'my_restrict_manage_posts' );
  3. function my_restrict_manage_posts() {
  4.  
  5.     // only display these taxonomy filters on desired custom post_type listings
  6.     global $typenow;
  7.     if ($typenow == 'books_ibm') {
  8.  
  9.         // create an array of taxonomy slugs you want to filter by - if you want to retrieve all taxonomies, could use get_taxonomies() to build the list
  10.         $filters = array('genre', 'writer');
  11.  
  12.         foreach ($filters as $tax_slug) {
  13.             // retrieve the taxonomy object
  14.             $tax_obj = get_taxonomy($tax_slug);
  15.             $tax_name = $tax_obj->labels->name;
  16.  
  17.             // output html for taxonomy dropdown filter
  18.             echo "<select name='$tax_slug' id='$tax_slug' class='postform'>";
  19.             echo "<option value=''>Show All $tax_name</option>";
  20.             generate_taxonomy_options($tax_slug,0,0);
  21.             echo "</select>";
  22.         }
  23.     }
  24. }
  25.  
  26. function generate_taxonomy_options($tax_slug, $parent = '', $level = 0) {
  27.     $args = array('show_empty' => 1);
  28.     if(!is_null($parent)) {
  29.         $args = array('parent' => $parent);
  30.     }
  31.     $terms = get_terms($tax_slug,$args);
  32.     $tab='';
  33.     for($i=0;$i<$level;$i++){
  34.         $tab.='--';
  35.     }
  36.     foreach ($terms as $term) {
  37.         // output each select option line, check against the last $_GET to show the current option selected
  38.         echo '<option value='. $term->slug, $_GET[$tax_slug] == $term->slug ? ' selected="selected"' : '','>' .$tab. $term->name .' (' . $term->count .')</option>';
  39.         generate_taxonomy_options($tax_slug, $term->term_id, $level+1);
  40.     }
  41.  
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement