Menü schliessen
Created: April 30th 2021
Last updated: December 10th 2021
Categories: Php,  Wordpress
Author: Tim Fürer

WordPress: Custom Column

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In this guide, I'll show you how to make custom columns for posts which show up in the WordPress Admin. You can use these to display values of custom fields for example.

Notes: You're free to change 'myCustomColumn' to any name you want the column to have and display. {post-type} is to be replaced with the target post-type and {custom-field} with the ID of the custom-field we want to take the value from.

Creating the WordPress custom column

function myCustomColumn_head($defaults)
{
	$defaults['myCustomColumn'] = 'myCustomColumn';
	return $defaults;
}
add_filter('manage_{post-type}_posts_columns', 'myCustomColumn_head');

The two strings in here, which currently have the value of  'myCustomColumn', are for defining the column's name.

Read more about this filter here.

Filling in the content for the column

function myCustomColumn_content($name, $post_ID)
{
	if ($name == 'myCustomColumn')
	{
		$post_meta = get_post_meta($post_ID,'{custom-field}',true);
	}

	if (!empty($post_meta))
	{
		echo $post_meta;
	}
}
add_action('manage_{post-type}_posts_custom_column', 'myCustomColumn_content', 10, 2);

Note: The function, on call, takes the column's name ($name) and the post's ID ($post_ID).

We start off the function with an if statement which checks for the name of the column to be 'myCustomColumn' before it gets the content. This is important if you have multiple columns as the content for every custom column is managed in this function, thus we need some sort of separation to not accidentally give column A the content of column B and vice versa. The second if statement checks if we did receive any content and if so, echo said content.

Read more about this action here.

Styling the column

function myCustomColumn_styles()
{
	echo '<style>.column-myCustomColumn{width:10%;}</style>';
}
add_filter('admin_head', 'myCustomColumn_styles');

This is very straight forward. Here, we just give the column a width of 10%.