WordPress Technique: Add Custom Column To The Posts List.

Blog Programming Tips-And-Tricks


Add Custom Column (Featured Image) to the Posts List in WordPress Admin.
Set a custom size of say, 55 pixels that will be used to show the featured image’s under Featured Image column:

add_image_size('featured_preview', 55, 55, true);

GET Featured Image of the provided Post Id.

function my_get_featured_image($post_ID) {
    $post_thumbnail_id = get_post_thumbnail_id($post_ID);
    if ($post_thumbnail_id) {
        $post_thumbnail_img = wp_get_attachment_image_src($post_thumbnail_id, 'featured_preview');
        return $post_thumbnail_img[0];
    }
}

And at last we define two functions: the first will add the new column (featured_image), the second will call and show the featured image in every cell of the new column.

// Add new Column to the Posts list (admin)
function my_columns_head($columns) {
    $columns['featured_image'] = 'Featured Image';
    return $columns;
}
 
// Render Featured Image under its column on each call.
function my_columns_content($column_name, $post_ID) {
    if ($column_name == 'featured_image') {
        $post_featured_image = my_get_featured_image($post_ID);
        if ($post_featured_image) {
            echo '<img src="' . $post_featured_image . '" />';
        }
    }
}

Now we are all set to hook our functions to WordPress’s plugin APIs.

add_filter('manage_posts_columns', 'my_columns_head');
add_action('manage_posts_custom_column', 'my_columns_content', 10, 2);

Leave a Reply

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