How To Add Custom Columns To The Posts List In The WordPress Admin
You can add your own columns to the list of posts, pages or custom post types in the dashboard, for example a thumbnail, a price or a custom field. Two hooks are needed: one to register the column and one to print its content.
Add a thumbnail column to a custom post type
The hook names contain the post type. For regular posts use manage_posts_columns and manage_posts_custom_column, and for pages use manage_pages_columns and manage_pages_custom_column.
function lotgrafix_portfolio_columns( $columns ) {
$new = array();
foreach ( $columns as $key => $label ) {
$new[ $key ] = $label;
if ( 'cb' === $key ) {
$new['lotgrafix_thumb'] = __( 'Image', 'lotgrafix' );
}
}
$new['lotgrafix_client'] = __( 'Client', 'lotgrafix' );
return $new;
}
add_filter( 'manage_lotgrafix_portfolio_posts_columns', 'lotgrafix_portfolio_columns' );
function lotgrafix_portfolio_column_content( $column, $post_id ) {
if ( 'lotgrafix_thumb' === $column ) {
echo get_the_post_thumbnail( $post_id, array( 60, 60 ) );
}
if ( 'lotgrafix_client' === $column ) {
echo esc_html( get_post_meta( $post_id, 'lotgrafix_client', true ) );
}
}
add_action( 'manage_lotgrafix_portfolio_posts_custom_column', 'lotgrafix_portfolio_column_content', 10, 2 );
Remove an existing column
function lotgrafix_remove_columns( $columns ) {
unset( $columns['comments'] );
unset( $columns['tags'] );
return $columns;
}
add_filter( 'manage_posts_columns', 'lotgrafix_remove_columns' );
Make a column sortable
function lotgrafix_sortable_columns( $columns ) {
$columns['lotgrafix_client'] = 'lotgrafix_client';
return $columns;
}
add_filter( 'manage_edit-lotgrafix_portfolio_sortable_columns', 'lotgrafix_sortable_columns' );
function lotgrafix_sort_by_client( $query ) {
if ( ! is_admin() || ! $query->is_main_query() ) {
return;
}
if ( 'lotgrafix_client' === $query->get( 'orderby' ) ) {
$query->set( 'meta_key', 'lotgrafix_client' );
$query->set( 'orderby', 'meta_value' );
}
}
add_action( 'pre_get_posts', 'lotgrafix_sort_by_client' );
Style the column width
function lotgrafix_admin_column_css() {
echo '<style>.column-lotgrafix_thumb{width:80px;}</style>';
}
add_action( 'admin_head', 'lotgrafix_admin_column_css' );


