Adding custom columns to the WordPress Posts/Pages listing

While developing your custom plugins you might may have desired to add extra columns to the pages/posts listing in WordPress admin section. At first glance you may think that it may requires editing some template file (I guessed same though ;)). But thanks to WordPress action api that allows you to manipulate nearly every action in WordPress. Adding custom column is also achieved through WordPress actions. Lets see how it is done.

In your theme’s function.php or your plugin file, write the following code:

add_filter('manage_posts_columns', 'my_column');

function my_column($defaults){

$defaults['my_column'] = __('Custom Column'); /*Add our column to the list of default columns*/

return $defaults;

}

The ‘manage_posts_columns‘ filter will add the custom column to the list of default columns. So the column heading now appears in the listing. But it has no data till now. To add data under this column, write following code:

add_action('manage_posts_custom_column', 'custom_column_data', 10, 2);

function custom_column_data($column_name, $id) {
if( $column_name == 'my_column' ) {

/*Fetch custom information saved in meta data for this post*/
$meta = get_post_meta($id, 'custom_info');

/*If metadata is not empty, show it in the column*/
if(!empty($meta)){

$reviewed_by = $meta['reviewed_by'];

$user = get_userdata($reviewed_by);

echo '<a href="'.site_url()."/wp-admin/edit.php?post_type=post&author=".$user->ID.'">'.$user->user_nicename.'</a>';

}

}
}

The action ‘manage_posts_custom_column‘ takes two arguments, one is the column name and other is the post ID. Based on these, any type of information can be shown in the column.

Managing Pages
To add the column to the pages listing, use following actions and filters:

add_filter('manage_pages_columns', 'my_column');

add_action('manage_pages_custom_column', 'custom_column_data', 10, 2);

Written by Arvind Bhardwaj

Arvind is a Magento and WordPress expert with more than 6 years of industry wide experience.

Website: http://www.webspeaks.in/

One thought on “Adding custom columns to the WordPress Posts/Pages listing

Comments are closed.