Deluxe Blog Tips About Projects

Add Custom Column To WordPress Post Manage Page

The post manage page in WordPress shows you a list of posts with their details: title, author, categories, etc. These details give blog manager a quick summary view of the posts. Sometimes, you might want to add new custom column to this page, such as 'Views', 'Ratings', custom post order, ... to see more statistics about posts, especially when you have installed the corresponding plugins. This article will show you how to do that.



Suppose that we're going to add a custom column 'Views' into post manage page. In this article, I use the WP-PostViews plugin (or you can use MB Admin Column extension of Meta Box plugin). This plugin adds a custom field into posts for storing number of views. We will get the value from this custom field and show it in post manage page.

Register custom column

First, we need to register a custom column to WordPress. This is done by using a filter manage_posts_columns as in the following code (paste it into your functions.php file):

add_filter('manage_posts_columns', 'my_columns');
function my_columns($columns) {
    $columns['views'] = 'Views';
    return $columns;
}

The function my_columns take an argument $columns which is an array of all registered columns. To add a new column, just add a new element to this array.

Note: You might want to show all available columns using print_r() or var_dump() functions. In addition, you can unset an element to remove a column or reorder columns.

This filter works fine, but it will add a new custom column to all post manage page, including for custom post type. So, to specify the manage page for a custom post type, we use another filter: manage_edit-customposttype_columns, where customposttype is the slug of you custom post type. For example, if you want to add a new column to manage page for post type film, just use:

add_filter('manage_edit-film_columns', 'my_columns');
function my_columns($columns) {
    $columns['views'] = 'Views';
    return $columns;
}

Show the new column

To show the new added column, we hook into the action manage_posts_custom_column. Add the following code into your functions.php file:

add_action('manage_posts_custom_column',  'my_show_columns');
function my_show_columns($name) {
    global $post;
    switch ($name) {
        case 'views':
            $views = get_post_meta($post->ID, 'views', true);
            echo $views;
    }
}

The hooked function takes one argument – name of the column. So, we need to check this name, if it's views (which we have registered before), than we get the custom field value and show it.

If your new column needs more information, such as show attachment, post thumbnail, … you can use any WordPress function to get these data and show it. The example above just shows you the concept, I keep it simple to make it clear to follow.

That's one among many application of custom fields.

Hope this tutorial is helpful for you.