Code to add a custom column to the WP Admin Posts listing page.
Example Code to add a Custom WordPress Column
namespace salcode\addPostMetaColumn;
add_filter( 'manage_post_posts_columns', __NAMESPACE__ . '\add_column', 20 );
add_action( 'manage_posts_custom_column', __NAMESPACE__ . '\render_column', 10, 2 );
/**
* Add thumbnail ID to posts display.
*
* @param array $columns Columns.
* @return array Updated columns.
*/
function add_column( $columns ) {
return array_merge(
array_slice( $columns, 0, 2, true ),
[
'thumbnail_id' => 'Thumbnail ID',
],
array_slice( $columns, 2, null, true )
);
}
/**
* Render the content for the thumbnail ID.
*
* @param string $column Column slug.
* @param int $post_id Post ID.
*/
function render_column( $column, $post_id ) {
if ( 'thumbnail_id' === $column ) {
echo esc_html( get_post_meta( $post_id, '_thumbnail_id', true ) );
}
}
Easy Mistake to Make
The biggest thing I forget is that I need to use the manage_post_posts_columns
hook (rather than manage_posts_columns
). Using the manage_posts_columns
hook applies my custom column to all post types (e.g. post
and custom post types).
Leave a Reply