Add Custom Column to Posts Admin Screen

If you want to add new columns to the posts overview, wordpress provides hooks to create custom columns and their associated data for a custom post type are manage_{$post_type}_posts_columns and manage_{$post_type}_posts_custom_column respectively, where {$post_type} is the name of the custom post type.

For Example, if you want to add Start and End Date Field in Event Post type list screen in admin, you need to add following code in functions.php file inside child theme:

function customdate_event_modify_columns( $columns ) {

  // New columns to add to table
  $new_columns = array(
	'start_date' => __( 'Event Start', 'customdate_textdomain' ),
	'end_date' => __( 'Event End', 'customdate_textdomain' )
  );
	
  // Remove unwanted publish date column
  unset( $columns['date'] );
  
  // Combine existing columns with new columns
  $filtered_columns = array_merge( $columns, $new_columns );

  // Return our filtered array of columns
  return $filtered_columns;
}

// Let WordPress know to use our filter
add_filter('manage_event_posts_columns' , 'customdate_event_modify_columns');

Please note that “customdate” here should be a unique name for your plugin or theme.

If you’ve completed step one above and looked at your edit.php screen, you’ll notice that your new column headings are there but that the cells underneath these columns are empty. now add following code in functions.php file in your child theme to display data on two custom columns:

function customdate_event_custom_column_content( $column ) {
  
  // Get the post object for this row so we can output relevant data
  global $post;
  
  // Check to see if $column matches our custom column names
  switch ( $column ) {

    case 'start_date' :
      // Retrieve post meta
      $start = get_post_meta( $post->ID, 'event_start', true );
      
      // Echo output and then include break statement
      echo ( !empty( $start ) ? date( "m/d/y h:i A", $start ) : '' );
      break;

    case 'end_date' :
      // Retrieve post meta
      $end = get_post_meta( $post->ID, 'event_end', true );
      
      // Echo output and then include break statement
      echo ( !empty( $end ) ? date( "m/d/y h:i A", $end ) : '' );
      break; 
      
  }
}

// Let WordPress know to use our action
add_action( 'manage_event_posts_custom_column', 'customdate_event_custom_column_content' );

After Then, You can see two new column start and end date with data. this can be very useful wordpress function. if you want to use any custom admin column in post list screen on admin.

Leave a comment