Custom columns for wordpress custom post type


/ Published in: PHP
Save to your folder(s)

This adds custom columns to a custom post type


Copy this code and paste it in your HTML
  1. add_filter( 'manage_edit-events_columns', 'my_edit_events_columns' ) ;
  2.  
  3. function my_edit_events_columns( $columns ) {
  4.  
  5. $columns = array(
  6. 'cb' => '<input type="checkbox" />',
  7. 'title' => __( 'Event' ),
  8. 'event-date' => __( 'Event Date' ),
  9. 'category' => __( 'Category' ),
  10. 'date' => __( 'Date' )
  11. );
  12.  
  13. return $columns;
  14. }
  15.  
  16. add_action( 'manage_events_posts_custom_column', 'my_manage_events_columns', 10, 2 );
  17.  
  18. function my_manage_events_columns( $column, $post_id ) {
  19. global $post;
  20.  
  21. switch( $column ) {
  22.  
  23. /* If displaying the 'duration' column. */
  24. case 'event-date' :
  25.  
  26. /* Get the post meta. */
  27. $event_date = get_post_meta( $post_id, '_event_date', true );
  28.  
  29. /* If no duration is found, output a default message. */
  30. if ( empty( $event_date ) )
  31. echo __( 'Unknown' );
  32.  
  33. /* If there is a duration, append 'minutes' to the text string. */
  34. else
  35. echo( $event_date );
  36.  
  37. break;
  38.  
  39. /* If displaying the 'genre' column. */
  40. case 'category' :
  41.  
  42. /* Get the genres for the post. */
  43. $terms = get_the_terms( $post_id, 'event-category' );
  44.  
  45. /* If terms were found. */
  46. if ( !empty( $terms ) ) {
  47.  
  48. $out = array();
  49.  
  50. /* Loop through each term, linking to the 'edit posts' page for the specific term. */
  51. foreach ( $terms as $term ) {
  52. $out[] = sprintf( '<a href="%s">%s</a>',
  53. esc_url( add_query_arg( array( 'post_type' => $post->post_type, 'event-category' => $term->slug ), 'edit.php' ) ),
  54. esc_html( sanitize_term_field( 'name', $term->name, $term->term_id, 'event-category', 'display' ) )
  55. );
  56. }
  57.  
  58. /* Join the terms, separating them with a comma. */
  59. echo join( ', ', $out );
  60. }
  61.  
  62. /* If no terms were found, output a default message. */
  63. else {
  64. _e( 'No Categories' );
  65. }
  66.  
  67. break;
  68.  
  69. /* Just break out of the switch statement for everything else. */
  70. default :
  71. break;
  72. }
  73. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.