WordPress: Add Post ID Column to Admin Listing Table

This is a tutorial on how to add new column in the posts table in the admin view.

What am I talking about?

See the image below. By default, wordpress doesn’t show the ID of the post or page.

The Script

Add the following script to your themes functions.php

{code type=”php”}

add_filter(‘manage_edit-post_columns’ , ‘custom_set_posts_columns’);
function custom_set_posts_columns($columns) {
return array(
‘cb’ => ‘<input type=”checkbox” />’,
‘id’ => __(‘ID’),
‘title’ => __(‘Title’),
‘author’ => __(‘Author’),
‘date’ => __(‘Date’),
);
}

add_action( ‘manage_posts_custom_column’ , ‘custom_set_posts_columns_value’, 10, 2 );
function custom_set_posts_columns_value( $column, $post_id ) {
if ($column == ‘id’){
echo $post_id;
}
}

add_action(‘admin_head’, ‘custom_admin_styling’);
function custom_admin_styling() {
echo ‘<style type=”text/css”>’;
echo ‘th#id{width:50px;}’;
echo ‘</style>’;
}

{/code}

Understanding each line

  • Line 1: filter manage_edit-post_columns to display our own set of columns
  • Line 2: custom_set_posts_columns is our custom function
  • Line 4,6,7,8: the default wordpress columns
  • Line 5: our new column. id will serve as our column identifier and ID will be our column title
  • Line 12: add action to manage_posts_custom_column to define our column id
  • Line 13: custom_set_posts_columns_value will be the function that would process the column id
    parameters: $column = the column identifier, $post_id = the post ID
  • Line 14: check if the current $column is our new column id. If yes, then:
  • Line 15: display $post_id
Yikes! the new column is so wide!
  • Line 20: add filter to the admin header section to display our custom column styling
  • Line 21: our styling function
  • Line 23: the css id of our <th>  tag would be the same as our identifier. add the desired column width
And we are done!

Any real life application?

This sample code is just a foundation in understanding on how you can actually customize the admin’s listing table.

Sometimes, your client may require you to display additional information in the listing page to serve as a quick view information to the end user.

For example, you can add a column that display the featured image of the post or any meta value.

The application really varies depending on your client’s needs or your theme features.

Hope you’ll find this useful.

:) Happy reading.

Recent Posts