Hack: Adding a Column With a Custom Field To the Admin Post List

So yesterday I showed you how to add a custom field to posts or pages, and then use that field to redirect the page to another URL. In the past I have used custom fields for other things too. I wanted to show this custom field redirect in the list of posts (actually, pages for my needs) so I can see which pages have a redirect.

This is a little tricky. First, you need to use the manage_pages_columns (or manage_posts_columns) hook to add a new column.

add_filter('manage_pages_columns', 'wpfilter_posts_columns');
function wpfilter_posts_columns($columns) {
  $columns = array_slice($columns, 0, 2, true) + array('redirecturl' => 'Redirect') + array_slice($columns, 2, NULL, true);
  return $columns;
}

It is easy to add to the end of the columns, but since I wanted it in the middle at position 2, I had to use two array_slice functions to get it in the proper spot.

Next, you need to use the manage_pages_custom_column to put the contents of the custom field in the column. You can use this to put pretty much anything in the column. I’m going to get the custom field redirecturl.

add_action('manage_pages_custom_column', 'wpaction_manage_pages_custom_column', 10, 2);
function wpaction_manage_pages_custom_column($columnname, $post_id) {
    $custom_fields = get_post_custom($post_id);
	if ($columnname == 'redirecturl') {
            echo $custom_fields['redirecturl'][0];
     }
}

Now I have a convenient way to see the value of that custom field as I scroll through my pages in the admin.

Leave a Reply

Your email address will not be published. Required fields are marked *