89 Responses

  1. shawn
    shawn Published |

    Request:
    Could you possibly expand your article on how to add a featured image/gallery iamge to the post column like the ‘movie poster’ where the post type is hierarchical?

    I spent most of the weekend trying to figure that part out. There are tons of articles on how to do this with a non-hierarchical post-type. But everyone said it was virtually impossible with hierarchical, so wait until wp 3.1, which of course is out now.

    Always learning something when I come to this site. What a great resource of information, thank you

    Reply
  2. The Frosty
    The Frosty Published |

    Great write up! I’ve done this in many themes already, but the request and sort part still messed me up. Thanks.

    Reply
  3. Piet Bos
    Piet Bos Published |

    Great tutorial, Justin, thanks! Finally managed to get it done as with previous tutorials there was always sth not going the way it should.

    One question: For my CPT (review) I use a taxonomy of Author Rating and in the description for those ratings I use images (stars). I can show them on the frontend, but it would of course also be very cool to be able to display them in the custom columns.

    I have tried to use $term->description in the line of esc_html, but that doesn’t seem to work for images (for “normal” descriptions it does work). How to accomplish this feat?

    Thanks!
    Piet

    Reply
    1. Piet Bos
      Piet Bos Published |

      sorry, a premature question, found the solution myself already. As it turned out I was trying it on the wrong line…

      I adapted the line that says: echo join( ‘, ‘, $out );

      into: echo $term->description;

      and that works perfect!
      Thanks again!

      Reply
  4. Dave Turnbull
    Dave Turnbull Published |

    Both your article and Joost’s are great – thanks. I wonder if it’d be something that either of you will look to turn into a plugin? Seems like a natural evolution given the usefulness of custom post types. Or is there a reason not to?

    Reply
  5. sanji
    sanji Published |

    Nice tutorial! Question: How can I display those genre in the front end? Like the way we display categories and pages. Thanks!

    Reply
  6. Ipixels Mediaworks
    Ipixels Mediaworks Published |

    I have a simple question someone might be able to answer. When I setup a custom post type, My “Show on Screen” under Screen Options, does not work anymore. I try displaying more than the 20 it has and it always reverts back to the 20. Is this happening to anyone else or is it just me?

    Reply
    1. Patrick Daly
      Patrick Daly Published |

      Works normally for me. I would bet that there is a Javascript conflict or error causing that though. Deactivate all of your plugins and switch to Twentyten. If that doesn’t fix it then there might be a database issue.

      Reply
      1. Ipixels Mediaworks
        Ipixels Mediaworks Published |

        Thanks Patrick for the quick response. But i have figured out the problem and just in case anyone ever has this problem this is the solution.

        You CAN NOT have a dash (-) in your register_post_type();

        I was trying to use register_post_type(‘our-work’, array(…
        and for some reason it did not like that. As soon as i changed it to ‘our_work’ or ‘work’ it works just fine.

  7. Jan Egbert
    Jan Egbert Published |

    Great write up Justin. I got stuck after playing with Joost de Valk’s ‘sortable snippet’. The columns seemed to be sortable, but really weren’t. This post helped me take the last step and make the columns sort the way I want them to sort. Only one question remaining for me. How do I change the default orderby parameter for a custom post type? Let’s say I have an even post type and I want my events to be ordered by start date by default. Any ideas on what’s the best way to do this?

    Reply
  8. Jan Egbert
    Jan Egbert Published |

    I ended up using this snippet for ordering post types by a unix timestamp in a custom field.

    function set_event_post_type_admin_order($wp_query) {
      if (is_admin()) {
    
        $post_type = $wp_query->query['post_type'];
    
        if ( $post_type == 'event') {
        	$wp_query->set('meta_key', 'bf_startdate');
          	$wp_query->set('orderby', 'meta_value_num');
          	$wp_query->set('order', 'DESC');
        }
    
      }
    }
    
    add_filter ( 'pre_get_posts', 'set_event_post_type_admin_order' );
    Reply
    1. Lukas
      Lukas Published |

      Thank you for this snippet Jan.
      I modified it a little to meet my requests:

      function set_video_post_type_admin_order($wp_query) {
        if (is_admin()) {
      
          $post_type = $wp_query->query['post_type'];
      
          if ( $post_type == 'video' && empty($_GET['orderby'])) {
            	$wp_query->set('orderby', 'date');
            	$wp_query->set('order', 'DESC');
          }
      
        }
      }
      add_filter ( 'pre_get_posts', 'set_video_post_type_admin_order' );

      I needed my custom posts to be ordered by date by default (for a strange reason default was order by title)
      I added empty($_GET['orderby']) to the if-clause since it didn’t anymore allow me to order it by title after I added the code to my theme functions.php

      Reply
  9. Daily Digest June 28th
    Daily Digest June 28th at |
  10. Tony Hadfield
    Tony Hadfield Published |

    Jan,

    To get a default sort order I used the following else to the initial check to see if the orderby is set:
    if ( isset( $vars['orderby'] ) && ‘duration’ == $vars['orderby'] )
    {
    ……
    }
    elseif ($vars['orderby'] == NULL )
    {
    /* Merge the query vars with our custom variables. */
    $vars = array_merge(
    $vars,
    array(
    ‘meta_key’ => ‘duration’,
    ‘orderby’ => ‘meta_value’,
    ‘order’ => ‘DESC’
    )
    );
    }

    Reply
  11. Danny G Smith
    Danny G Smith Published |

    You wouldn’t happen to know the field name for last updated date would you so I could add it’s column as well? I had looked all over for the published date, thanks for including it!

    Reply
  12. Dino Latoga
    Dino Latoga Published |

    Absolutely helpful tutorial. It’s just what I needed for my upcoming project. Added Devpress to my important bookmarks. Keep those helpful tutorials coming Justin.

    Thanks!

    Reply
  13. Zach
    Zach Published |

    Great writeup! Wondering how this might be adapted to front-end filter/sort controls (for example, sorting by the duration on the front-end, or filter by a certain duration time). Thanks!

    Reply
  14. Custom Columns for Custom Post Types | Mark Wilkinson on WordPress
  15. Diogo
    Diogo Published |

    Great advice!

    Have you tried to make the column sortable without modifying the query vars?

    I’ve just followed your steps but actually tried to sort by the new column before I added the filter to ‘request’ and it just worked, even with pagination. The column I added was from a meta data just as yours, and clicking on the header sorts them just fine.

    Is it really necessary to modify the query vars then? How is it automatically guessing?

    My biggest concern is that since it worked for me automatically, I tend to assume Wordpress queries all posts and then sort and paginate them manually. I mean how could it work otherwise without manually configuring the query logic?

    And if so, how exactly modifying the query args avoid querying everything?

    I wish I could debug it a bit further but I’m really fresh to Wordpress.

    wbr,
    Diogo

    Reply
  16. Simon
    Simon Published |

    Superb write up.

    The next obvious question is regarding order:
    Is it possible to order the Genre column?
    Not necessarily by clicking on the column heading “Genre” but when you click e.g “Science Fiction” you would expect to see all posts that are in taxonomy Science Fiction to be ordered first.

    Is this possible?

    Reply
    1. rzen
      rzen Published |

      +1 for this. I would love to know how to sort a post based on taxonomy. I realize the difficulty based on the fact that a post could potentially belong to multiple taxonomies, but that wouldn’t be the case for my current scenario.

      Reply
  17. Mango
    Mango Published |

    If I want sortable the “genre” columns by name? Is taxonomy. Is possible?

    Reply
  18. Custom columns for custom post types | the Beard of Inspiration
  19. Radu
    Radu Published |

    I was wondering if I could get any support. I followed the tutorial to add a custom column to display the post parent for a custom post type I created. The post parent of each post displays very nicely. I used:

    $var1 = get_post($post_id)->post_parent;
    $var2 = get_post($var1)->post_title;
    echo $var2;

    to display the title of the post parent.
    What I would like to do more is to make each post parent clickable so that only post with that post parent are displayed, just like you do with the “genre” column in your tutorial.
    I tried something like:

    $varurl = add_query_arg(array(‘post_type’ => $post->post_type, ‘post_parent’ => $var1), ‘edit.php’);
    echo ‘‘.$var2.’‘;

    but even though the each post parent is now clickable and the url shows something like: “/edit.php?post_type=my_type&post_parent=post_parent_ID”, when clicking on a post parent I still get all the other posts.
    How can I make this work properly?
    Thx,
    Radu

    Reply
  20. How can I filter posts by post_parent in the admin? | SeekPHP.com
  21. Clarence
    Clarence Published |

    I want to adopt you. Thanks for this post.

    Reply
  22. WordPress Custom Post Types Tutorials, Tools & Advice | Customize WordPress Blog
  23. dave
    dave Published |

    thank God for this article.

    Reply
  24. Dennis Smolek
    Dennis Smolek Published |

    I’m having some issues with the custom attributes. When I click on the attribute it takes me to the edit page, but isn’t passing the post type so it loads “posts” by default, so naturally my cpt’s arn’t there.

    I copied your snippet exact, changed Genre to my cpt name and its all showing great, except the clicking thing..

    Reply
  25. Dennis Smolek
    Dennis Smolek Published |

    I figured out what I did. I didn’t have the global $post.

    Reply
  26. mad
    mad Published |

    thank you!

    Reply
  27. Alessio
    Alessio Published |

    How to sort taxonomy by ID and not by name?

    Reply
  28. Custom columns for custom post types
    Custom columns for custom post types at |
  29. Most Helpful Web Development Posts In 2011 :: TechBasedMarketing
  30. Nancy
    Nancy Published |

    Hi,
    This is really helpful… I’ve gotten the columns to work, but I have a related question that I can’t seem to figure out.

    I changed the Author field to “Client” in the columns, but how do I also change that label on the Edit page for my custom post type?

    much appreciated!

    Reply
  31. Ido Schacham
    Ido Schacham Published |

    Thanks for the helpful tutorial. +1 for how to order columns by taxonomy, genre in this case.

    Reply
  32. WPSmith | Developing a Custom Post Type and a Custom Taxonomy in Genesis with Custom Pages, Part 5
  33. Kat
    Kat Published |

    Fantastic post. I’ve got it working for one custom variable. I’ve got multiple custom field columns and am stuck on the adding in extra sortable columns in the my_sortable_columns function. How do I define multiple sortable columns?
    Thanks!

    Reply
  34. How I Built Code Snippets With Custom Post Types
  35. Parin
    Parin Published |

    Was looking for a way to do this after reading your custom post types article and adding some custom post types – thanks again Justin. Appreciate the detailed steps.

    Reply
  36. Elle
    Elle Published |

    I’ve implemented this code, and the second snippet to set the default sort order, however I’d like to remove the ability to sort by title or date – ie. I want a fixed sort order, how can I take that functionality off? Thanks for an excellent tutorial!

    Reply
  37. David S.
    David S. Published |

    Thx a lot ! It was really helpfull !

    Reply
  38. Munzir
    Munzir Published |

    thanks for the tutorial! really helpful!

    Reply
  39. Geert De Deckere
    Geert De Deckere Published |

    Is manage_edit-{$post_type}_columns still the preferred hook for adding columns? I’m using manage_{$post_type}_posts_columns.

    Reply
  40. Developing a Custom Post Type and a Custom Taxonomy in Genesis with Custom Pages, Part 5 - WP Smith
  41. Modificare le colonne visualizzate nel backend wordpress | openbrain
  42. Add custom column and custom data to Wordpress admin | Web Animals
  43. Sorting and Searching by Metadata on WordPress Post Overview Pages | Buzu’s Oficial Blog
  44. Carrie Dils
    Carrie Dils Published |

    Just now joining the party on this post. Thank you for the great detail and the commenting throughout your code. Just tried it on my own CPT with success!

    Reply
  45. wordpress给后台文章列表增加自定义排序栏 - 李应青那点事
  46. virginalforces
    virginalforces Published |

    Hi,

    Thanks for this wonderful tutorial.

    My question is : How can I keep the original “comment number” columns in the manage_edit-{$post_type}_columns related function?

    using 'comments' => __( 'Comments' ) give me the comment number but without ‘graphics’….

    Reply
  47. Rob
    Rob Published |

    Thanks for the article, really helped me out.

    I have a question about sorting… Is it possible to sort by two columns? I’ve got two postmeta fields, selected_date and selected_time. Displaying the content, I concatenate the two into one column (YYYY-MM-DD hh:mm). Ideally, if I’m sorting by that column, I’d like to sort it by both date and time – currently I’ve got it sorting only by date, following your instructions above.

    I tried merging a second array, but that didn’t seem to do anything.

    Reply
  48. Bill Seymour
    Bill Seymour Published |

    Great article, thanks. My Q: Is it possible to do a ‘double sort’ using two custom fields? Example: I have an Apartments CPT, with CF’s Listed and AptNumber. Can one order columns first by Listed, further sorted by AptNumber?

    Reply
  49. Kelvin
    Kelvin Published |

    Hi, thanks for the tutorial, its really helpful and i manage to display the columns on my custom post type but i would like to know how will you be able to display selected options from an array of checkboxes. The custom field thats housing the checkboxes is called “region”. I have attempted using the codes below but in return, it showed me the word, “array” instead of the selected checkbox. Is there anyway around this? Some assistance or advice would be helpful. Cheers :D

    /* If displaying the 'region' column. */
    		case 'region' :
    
    			/* Get the post meta. */
    			$region = get_post_meta( $post_id, 'region', true );
    
    			/* If no product_code is found, output a default message. */
    			if ( empty( $region ) )
    				echo __( 'TBA' );
    
    			/* If there is a region. */
    			else
    				printf( __( '%s' ), $region );
    
    			break;
    Reply
  50. Aristotle
    Aristotle Published |

    Great article Justin! Great for learning some more advanced php, very clear breakdown. However, it’s funny how i actually for the first time in my life wanted to apply a facebook like for your post, and i can’t!! But thanks for the trouble anyway, and this form is so irritating, 4th attempt for posting a comment, hope you dont use it for all your sites..

    Reply
  51. Curtis F
    Curtis F Published |

    Awesome post! I think it’s the best one I’ve found on custom columns for WordPress admin!

    Reply
  52. Drew Adcock
    Drew Adcock Published |

    I needed this tut!

    However, I am getting a strange result on the sort. It seems to be sorting by the date – not my custom field?

    I tried to stay as close to your code as possible – but must have missed something

    add_filter( 'manage_edit-hymn_columns', 'hymn_admin_columns' );
    function hymn_admin_columns( $columns ){
    
    	$columns = array(
    		'cb' => '',
    		'title' => __( 'Hymn' ),
    		'number' => __( 'Trinity Hymnal' ),
    		'category' => __( 'Category' ),
    		'rating' => __( 'Rating' ),
    		'date' => __( 'Date' )
    	);
    
    	return $columns;
    }
    
    add_action( 'manage_posts_custom_column', 'populate_columns', 10, 2 );
    function populate_columns( $column, $post_id ){
    	global $post;
    	
    	switch( $column ) {
    		case 'number' :
    			$hymn_info = get_post_meta(get_the_ID(), 'hymn_info', true); 
    			$hymn_number = $hymn_info['hymn_number'];
    			echo __( $hymn_number );		
    		break;
    		case 'category' :
    			$hymn_category = get_the_term_list( get_the_ID(), 'hymn_category', '', ', ', '' ); 
    			echo __( $hymn_category );
    		break;
    		case 'rating' :
    			$hymn_rating = wp_gdsr_rating_article(get_the_ID());
    			print_r($hymn_rating->rating);		
    		break;
    		default :
    		break;
    	}
    
    }
    
    add_filter( 'manage_edit-hymn_sortable_columns', 'my_hymn_sortable_columns' );
    
    function my_hymn_sortable_columns( $columns ) {
    
    	$columns['number'] = 'TrintyHymnalNumber';
    
    	return $columns;
    }
    
    add_action( 'load-edit.php', 'my_edit_hymn_load' );
    
    function my_edit_hymn_load(){
    	add_filter( 'request', 'my_sort_hymns' );
    }
    
    function my_sort_hymns( $vars ){
    	/* Check if we have the 'hymn' post type. */
    	if ( isset( $vars['post_type'] ) && 'hymn' == $vars['post_type'] ){
    		if ( isset( $vars['orderby'] ) && 'number' == $vars['orderby'] ){
    			$vars = array_merge(
    				$vars,
    				array(
    					'meta_key' => 'TrintyHymnalNumber',
    					'orderby' => 'meta_value_num'
    				)
    			);
    		}
    	}
    	return $vars;
    }
    Reply
  53. brent
    brent Published |

    Anybody know how to sort by two or more columns that are both meta_values ?

    ie:

    $vars = array_merge( $vars, array(
    		'meta_key' => 'session_day, session_room, session_time_slot',
    		'orderby' => 'meta_value, meta_value, meta_value'
    	));

    does not work

    $vars = array_merge( $vars, array(
    		'meta_key' => 'session_day session_room session_time_slot',
    		'orderby' => 'meta_value meta_value meta_value'
    	));

    does not work

    can’t merge multiple arrays of the single values because the arry keys would overwrite… :\

    Reply
    1. brent
      brent Published |

      forgot to mention that, I’m trying to modify the default sort order based on multiple meta values.

      oh, and thanks for any and all help in advance.

      Reply
  54. John
    John Published |

    Effin’ Awesome. Still.

    Reply
  55. Wordpress给后台文章列表增加自定义排序栏 | WordPress中文网
  56. Sebastian
    Sebastian Published |

    This is a great tutorial, Justin. It helped me a lot with the creation of my cms features within Wordpress. Thank you!

    What I don’t understand is why you are saying:

    “The next step is where everything gets a little trickier. We need to add a filter to the request hook but only filter it when viewing this specific screen in the WordPress admin.”

    add_action( 'load-edit.php', 'my_edit_movie_load' );

    (… and all the additional code you have shown in this context …)

    Why is that?

    What I did is just this:

    // Make these columns sortable
    
    function sortable_review_module_columns() {
    
    return array(
    
    'date' => 'date',
    
    'title' => 'title',
    
    'review_category' => 'review_category',
    
    'residence' => 'residence',
    
    'date_of_stay' => 'date_of_stay',
    
    );
    
    }
    
    add_filter( "manage_edit-review-module_sortable_columns", "sortable_review_module_columns" );

    With that I got all the columns that I think needed to be sortable as sortable.

    Did I miss something? Is it necessary to reduce this method to a certain edit screen?

    Reply
  57. Benno
    Benno Published |

    @Sebastian

    It makes them sortable, but it will only sort by postdate. The other function is to tell what value to use when sorting the column.

    And this is were my question for Justin (that has already been asked a few times the last years but has never been answerd): How would you make the ‘Genre’ column sortable?

    Reply
  58. Chetan
    Chetan Published |

    This helped me a lot – thank you very much for the wonderful post :)

    Reply
  59. Damien Carbery
    Damien Carbery Published |

    This is one of the articles I referenced when developing CPT for a site back in 2011. At the time I just couldn’t get it to work.

    I revisited the issue a year later and found the issue – my cpt name used dashes (bc-special-offers) – a habit from filenames when working on GNOME. When I changed them to underscores (bc_special_offers) it all worked fine. I had to edit the post_type column in the wp_posts table for the older posts but it finally worked.

    I have yet to find a reason for the problem, though I admit that I haven’t searched through the WordPress sources. I suppose I should submit an update to the register_post_type Codex page.

    Reply
  60. Richard Mišenčík
    Richard Mišenčík Published |

    Thanks, I have one question tho. How to change the order of the columns? Because when I just add new columns instead of overwriting everything, the date column is now first and my custom columns are after that. I want my custom columns first and the date column as last one (which is the default behaviour).

    Reply
  61. Jan
    Jan Published |

    The column “Genre” is not sortable. Please check your code.

    In fact the ‘request’ filter is never called on the taxonomy page, neither the ‘pre_get_post’ action.

    Reply
  62. Custom columns for a custom post type: Part 2 | brettrawlins.com
  63. Sorting and filtering on custom columns | brettrawlins.com
  64. Sarah Hills
    Sarah Hills Published |

    I too was having issues with rows being hidden where no value existed for the meta_value being sorted on.

    After searching for ages, here’s what seemed to fix it:

    ‘$meta_query = array(

    ‘relation’ => ‘OR’,

    array(

    ‘key’ => ‘property_reference’,

    ‘value’ => false,

    ‘type’ => ‘BOOLEAN’,

    ),

    array(

    ‘key’ => ‘property_reference’,

    ‘compare’ => ‘NOT EXISTS’,

    ‘value’ => ”,

    ),

    array(

    ‘key’ => ‘property_reference’,

    )

    );

    $query->set( 'meta_query', $meta_query );
    $query->set( 'meta_key', 'property_reference' );
    $query->set( 'orderby', 'meta_value' );'

    …where property_reference is my custom field value.

    Reply
    1. carrie dils
      carrie dils Published |

      Thanks for your comment as the empty value clued me in as to why rows went missing.

      Still tinkering with the meta_query per your example, but not getting it to work quite yet.

      Reply
  65. Wordpress | Pearltrees
    Wordpress | Pearltrees at |
  66. Lucas Moreira
    Lucas Moreira Published |

    Very helpful post!! Thanks!!

    Reply
  67. Sagive
    Sagive Published |

    Hey justin,

    i have visited this page many times and use it as a ready to go snipper…

    However, i would love it if in the end your have “the complete code” snippet. think about that ;) it is helpfull…

    Cheers,

    Sagive

    Reply
  68. Emerson
    Emerson Published |

    Great post! Still saving the day three years later!

    Any tips on making the custom columns searchable as well? It seems that by default the search field only looks at title and permalink, but it would be very nice to search by custom fields too.

    Reply
  69. Emerson
    Emerson Published |

    Huh. Discovered one more fly in the ointment: If you don’t include a “Title” column there is no link to edit the individual posts because the links for “Edit”, “Trash”, etc are exposed when you hover over the title. I’m guessing this can be side-stepped by renaming one of the columns “Title” but I haven’t tried yet. It would be better if there was a way to designate a new column to attach the links to. Anyone have any ideas?

    Reply
  70. Ben Chung
    Ben Chung Published |

    Great article.

    Was a little hard to find something on editing custom post type review/sort pages but this really nailed what I was looking for.

    Thanks!

    Ben.

    Reply
  71. Krissz
    Krissz Published |

    Hi,

    I’m usually never leave a comment for an article, but in this case, you save my life!! :) This article was amazing, helpful and very clear. Thank you!

    Reply

Leave a Reply

By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution.

Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.

css.php