Best Practice to Add WordPress Custom Post Columns in All Posts List – WordPress Tutorial

By | September 28, 2019

WordPress will display post title, author, comments columns et al in all posts list, we can remove some columns we do not want to display. You can read this tutorial to know how to remove.

Best Practice to Remove WordPress Post Columns in All Posts List – WordPress Tutorial

Meanwhile, we also can add some custom post columns to the all posts list. In this tutorial, we will introduce how to add our custom post columns.

To add our custom columns, we shoud use 2 steps:

1.Create a custom post column

2.Set the content of this custom post column

To add a post thumbnail column for example.

Create a custom post thumbnail column

Open your theme functions.php and add code below.

add_filter('manage_posts_columns', 'add_thumbnail_column');
function add_thumbnail_column($defaults) {
    $defaults['thumbnail'] = 'Thumbnail';
    return $defaults;
}

Then we will add a post thumbnail column (thumbnail) to all posts list. However, this column contains nothing, we should set the content for it.

Set the custom post thumbnail column content

You can add content below in your theme functions.php.

add_action('manage_posts_custom_column', 'add_thumbnail_column_content', 10, 2);
function add_thumbnail_column_content($column, $post_id) {
    if($column == 'thumbnail') {
	$p=get_post($post_id);
	$content = $p->post_content;
        $img_url = getFirstImageURL($content);
        
	echo "<img width=220 src='".$img_url."'/>";
    }
}

In this example code we set column content by column name (thumbnail), here we should set content for thumbnail column, then you should notice getFirstImageURL($content) is our custom function, the aim of this function is to extract the first image url from a post content, you can use other way to get image url.

Then you will find the result like this.

wordpress custom post thumbnail column

Leave a Reply

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