Add custom column and custom data to WordPress admin


22 November 2012 Author

Today I worked on columns of the wordpress edit posts page in admin.
I ‘ve got a custom post for events and my desire was to add a new column with some extra contents like the programmed day for each event.

Here you can see the final result: I added a new column “Data di Inizio” (start date) which is the programmed day for the event and I changed the title of the last column from “Data” to “Postato il” (Posted on) to not let the contributors confused between “Data” and “Data di inizio”.

To manage colums and titles you can use this hook:

add_filter( 'manage_edit-{custom-post-name}_columns', 'function_to_run' );

Be sure to put your custom post name in the brackets.

My solution was:

function colonna_eventi( $columns ) {

	$columns = array(
		'cb' => '<input type="checkbox" />',
		'title' => __( 'Evento' ),
		'datainizio' => __( 'Data di Inizio' ),
           'author' => __( 'Autore' ),		
		'date' => __( 'Postato il:' )

	return $columns;

add_filter( 'manage_edit-eventi_columns', 'colonna_eventi' ) ;

On line 6 I added the new column ‘Data di Inizio’ and on line 8 I changed the title of the date column in “Postato il”.

Now we have the new column but empty, if you look at the edit post page you can see the title in the head of the table but the entire column don’t print back any data.

To add content to the column we use another hook provided by wordpress.

	add_action( 'manage_{custom-post-name}_posts_custom_column', 'function_to_run', 10, 2 );

 The function that must be run uses a switch to add data to any column added (just one in my case ) and gets data from DB with the use of get_post_meta.

I wrote:

function dati_colonna_eventi( $column, $post_id ) {
	global $post;

	switch( $column ) {

           case 'datainizio' :

$datacalcolo = get_post_meta( $post_id, 'anno_evento', true ) . "/" . get_post_meta( $post_id, 'mese_evento', true ) . "/" . get_post_meta( $post_id, 'giorno_evento', true );
$now = date('Y/m/d', strtotime("now"));
$checkdate = date('Y/m/d', strtotime($datacalcolo));

if ( empty( $checkdate ) )

      echo __( 'Sconosciuto' );


      if ($checkdate >= $now) {	

        echo "<strong style='color:green'>" . $checkdate . "</strong>"; }                      

      else {

        echo "<strong style='color:#bbb'>" . $checkdate . "</strong>";}


		default :

	add_action( 'manage_eventi_posts_custom_column', 'dati_colonna_eventi', 10, 2 );

Lines 7,8,9 get the data from database and convert it in a date format so I can confront them with the current date and print the future dates in green color as I’ve done in lines 17-21.

Now I’m working on making the column sortable, I’ll keep you updated.
Everything learned here


Comments are closed.