Advertisement
Creative Coding

Add a Custom Column in Posts and Custom Post Types Admin Screen

by

In this tutorial we will see how to add a new column to the WordPress Posts management screen and in this column we will show the Featured Image of each Post. This new column will also be added in the management screen of any active Custom Post Type.


Step 1 Activate Featured Images

In this tutorial we will use the functions.php file available in our active theme directory. If the file is not present, you can create a new one with the following contents:

<?php
// FUNCTIONS

?>

First of all, check if the Featured Image is available on the Add New Post page:

If you don't see the Featured Image box, add this line to functions.php:

add_theme_support('post-thumbnails');

We also set a custom size of 55 pixels that will be used to show the featured image's preview:

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

Step 2 Add Custom Column to the Posts Screen

Now we'll add a new column in the Posts list table that will contain the featured image of each Post. But first, we need a function to get the featured image of a Post: ST4_get_featured_image.

Open the functions.php file in your theme directory and paste this:

// GET FEATURED IMAGE
function ST4_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 we define two functions: the first will add the new column, the second will call and show the featured image in every cell of the new column:

// ADD NEW COLUMN
function ST4_columns_head($defaults) {
	$defaults['featured_image'] = 'Featured Image';
	return $defaults;
}

// SHOW THE FEATURED IMAGE
function ST4_columns_content($column_name, $post_ID) {
	if ($column_name == 'featured_image') {
		$post_featured_image = ST4_get_featured_image($post_ID);
		if ($post_featured_image) {
			echo '<img src="' . $post_featured_image . '" />';
		}
	}
}

These two functions will be "hooked" into the WordPress core function that creates the Posts table.

About WordPress Hooks

Developers can modify WordPress default behavior through the WordPress APIs:

Hooks are provided by WordPress to allow your plugin to 'hook into' the rest of WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion.

In short, Hooks allow developers to extend WordPress features without editing core files. There are two types of Hooks: Actions and Filters. Both are launched during WordPress execution, but while Filters accept, transform and return an input, Actions return nothing, though can print everything you need.

In our case, the ST4_columns_head function takes the $defaults array that contains the default Posts table columns (Title, Category, Tags and so on...), adds a new featured_image item to the array and returns it to the core function that WordPress uses to print the table html.

On the contrary, the ST4_columns_content function accepts two variables ($column_name and $post_ID), and – depending on them – prints an output. To be more precise, ST4_columns_content is invoked on each iteration of the loop that traverses the $defaults array. On each iteration, WordPress passes two arguments to our function: the column name and the post ID. The function analyzes all column names and when the name is equal to the one we specified in ST4_columns_head, checks for featured image.

So, now we can hook our functions to WordPress plugin APIs:

add_filter('manage_posts_columns', 'ST4_columns_head');
add_action('manage_posts_custom_column', 'ST4_columns_content', 10, 2);

The 10 and 2 parameters are respectively: the order (priority) in which the function will be executed, and the number of arguments that the function accepts. Anyway, you can read more in the WordPress Codex under add_action.


Final Result

Now we can finally write a Post with a Featured Image:

So, when you open the manage Posts screen in /wp-admin/edit.php, you'll see the new Featured Image column:

First two posts have the featured image, the third (a post without a featured image) does not, so nothing is displayed.

To show a default image for posts that don't have a featured image, you can modify the ST4_columns_content function this way:

<?php
function ST4_columns_content($column_name, $post_ID) {
	if ($column_name == 'featured_image') {
		$post_featured_image = ST4_get_featured_image($post_ID);
		if ($post_featured_image) {
			// HAS A FEATURED IMAGE
			echo '<img src="' . $post_featured_image . '" />';
		}
		else {
			// NO FEATURED IMAGE, SHOW THE DEFAULT ONE
			echo '<img src="' . get_bloginfo( 'template_url' ); . '/images/default.jpg" />';
		}
	}
}
?>

The default.jpg image must be present in the images directory of our active theme.

You can also show / hide this new column by opening the Screen Options panel and clicking the Featured Image checkbox:


Step 3 Add the Featured Image Column to Custom Post Types

One of the most interesting and useful features of WordPress, is the possibility to add Custom Post Types (and also Custom Taxonomies). You can use post types to create new kinds of content, different from Posts and Pages, for example to manage a Movie database. In fact, when you add a custom post type, WordPress creates all the management pages for that post type: you can add, edit and delete those posts in the same way as default Posts and Pages.

Now we create a new Custom Post Type: Movies, through the WordPress register_post_type function:

add_action('init', 'ST4_add_movies');  

function ST4_add_movies() {
	$args = array(
		'label' => __('Movies'),
		'singular_label' => __('Movie'),
		'public' => true,
		'show_ui' => true,
		'capability_type' => 'post',
		'hierarchical' => false,
		'rewrite' => true,
		'supports' => array('title', 'editor', 'thumbnail')
	);
	register_post_type( 'movie' , $args );
}

So, when you add a featured image to a Movie post...

... you will see the featured image also in the manage Movies screen (note that also here you can show / hide the column in the Screen Options):


Other Usages

Adding the Custom Column Depending on Post Type

If you use the manage_posts_columns and manage_posts_custom_column hooks, the column will be shown in all manage posts screens. These filters in fact will work for posts of all types except Pages.

// ALL POST TYPES: posts AND custom post types
add_filter('manage_posts_columns', 'ST4_columns_head');
add_action('manage_posts_custom_column', 'ST4_columns_content', 10, 2);

If you want to add a column only in the manage Posts screen use:

// ONLY WORDPRESS DEFAULT POSTS
add_filter('manage_post_posts_columns', 'ST4_columns_head', 10);
add_action('manage_post_posts_custom_column', 'ST4_columns_content', 10, 2);

If you want to add a column only in the manage Pages screen use:

// ONLY WORDPRESS DEFAULT PAGES
add_filter('manage_page_posts_columns', 'ST4_columns_head', 10);
add_action('manage_page_posts_custom_column', 'ST4_columns_content', 10, 2);

If you want to add a column only in the manage Movies screen use:

// ONLY MOVIE CUSTOM TYPE POSTS
add_filter('manage_movie_posts_columns', 'ST4_columns_head_only_movies', 10);
add_action('manage_movie_posts_custom_column', 'ST4_columns_content_only_movies', 10, 2);

// CREATE TWO FUNCTIONS TO HANDLE THE COLUMN
function ST4_columns_head_only_movies($defaults) {
	$defaults['directors_name'] = 'Director';
	return $defaults;
}
function ST4_columns_content_only_movies($column_name, $post_ID) {
	if ($column_name == 'directors_name') {
		// show content of 'directors_name' column
	}
}

Add the Custom Column to Another Post Type

If you have other Custom Post Types, you can easily add the featured image column to them.
If you added the post type manually, check the file where the custom post is added and look for the first argument of the register_post_type function:

register_post_type( 'book' , $args ); // book is the post type

If the custom post type is defined through another plugin and/or you can't find where the register_post_type is, open the Custom Post management screen in your browser and check the URL:

http://www.yoursite.com/wp-admin/edit.php?post_type=book

In this case, book is the post type.

Finally, modify the hooks this way, replacing movie with book:

add_filter('manage_book_posts_columns', 'ST4_columns_book_head');
add_action('manage_book_posts_custom_column', 'ST4_columns_book_content', 10, 2);

Don't forget to create two functions: ST4_columns_book_head to create the column, and ST4_columns_book_content to display the content.

Add Two Custom Columns

If you need to add more than one column, you can easily do this:

// ADD TWO NEW COLUMNS
function ST4_columns_head($defaults) {
	$defaults['first_column']  = 'First Column';
	$defaults['second_column'] = 'Second Column';
	return $defaults;
}

function ST4_columns_content($column_name, $post_ID) {
	if ($column_name == 'first_column') {
		// First column
	}
	if ($column_name == 'second_column') {
		// Second column
	}
}

Remove Default Columns

You can also remove a WordPress default column, for example the Category column in the Posts management screen:

add_filter('manage_post_posts_columns', 'ST4_columns_remove_category');

// REMOVE DEFAULT CATEGORY COLUMN
function ST4_columns_remove_category($defaults) {
	// to get defaults column names:
	// print_r($defaults);
	unset($defaults['categories']);
	return $defaults;
}

References

Related Posts
  • Code
    Creative Coding
    Advanced Use of Attachments in WordPress: Assigning Categories and Taxonomy Terms to AttachmentsAdvanced use of attachments in wordpress 400
    This tutorial is the first in a four part series in which you'll learn some techniques for working with images in attachments in WordPress which give you advanced options. Read More…
  • Code
    Creative Coding
    Using WordPress for Web Application Development: Understanding Events, Actions, and FiltersApplication foundation 400
    Throughout this series, we've been taking a look at how WordPress can be used for building web applications. Up to this point, we've established that WordPress is a foundation - rather than a framework - and we've talked a bit about how we need to avoid trying to shoehorn WordPress into another type of design pattern than that of its native type.Read More…
  • Code
    Creative Coding
    Customizing the WordPress Admin - Listings ScreensCustomize wordpress admin rachel 400
    In Parts 1-4 of this series I showed you how to: Customize the WordPress login screen Customize the dashboard Customize the admin menu Add help text to post editing screens In this fifth instalment I'll show you how to customize listings screens in the admin.Read More…
  • Code
    Creative Coding
    How to Modify the Parent Theme Behavior Within the Child ThemeHow to modify the parent theme behavior within the child theme
    What are child themes? Child themes are a useful WordPress feature that allows developers to build a new template without starting from scratch, but by taking advantage of all the features already available in an existing theme. Sometimes however, the parent theme we have chosen for our site may have some features that we don't need (or we need to customize to best suit our needs), for example custom post types with a different slug, Shortcodes, JavaScript libraries, image sizes that we don't use and so on...Read More…
  • Code
    Creative Coding
    Plugin Templating within WordPressPlugin templating within wordpress
    When it comes to creating a Custom Post Type within a WordPress plugin, there's always the same problem: you need to create a custom single-[cpt_slug].php file in your theme folder if you don't want to use the default single.php file from your theme. In this post I'd like to cover two aspects of using custom templates. The first step is to show that we can use a custom file contained directly in the plugin itself instead of loading the default single.php, and the second one is how to create your own custom file in your theme folder.Read More…
  • Code
    Tips
    Quick Tip: Add Custom Columns in WordPress Manage ScreensCover
    This quick tip explains how to add a Custom Column in the Manage Screens of your WordPress blog.Read More…