Could we help you? Please click the banners. We are young and desperately need the money
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.
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.
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.
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%.