Support Forum
Support › MB Admin Columns › Displaying Featured Image in Admin ColumnsResolved
Hi guys,
I have followed along with some custom code I found in this forum trying to display the featured_image in the admin columns before the Title. But it breaks my site.
I don't have a theme, so I don't use functions.php. Instead I use Code Snippets to add custom PHP.
Is there some code somewhere that provides a working example of how to display the featured image in the Admin Columns?
Thanks for your time.
John Anderson.
Hi John,
Please try this snippet:
add_action( 'admin_init', function() {
class My_Featured_Image_Columns extends MB_Admin_Columns_Post {
public function columns( $columns ) {
$columns = parent::columns( $columns );
$position = 'before';
$target = 'title';
$this->add( $columns, 'featured_image', 'Featured Image', $position, $target );
// Add more if you want
return $columns;
}
public function show( $column, $post_id ) {
switch ( $column ) {
case 'featured_image':
the_post_thumbnail( [40, 40] );
break;
// More columns
}
}
}
new My_Featured_Image_Columns( 'post', array() );
} );
Oh! I love you!!! lol.
And you updated the documentation for Admin Columns with this example! Now I just change the 'post' slug to what ever slug my CPT is and it will display the featured image in the admin columns.
Thank you!
Just one last question.
new My_Featured_Image_Columns( 'post', array() );
when I instantiate the class, how would I do so for more than 1 CPT? I tried this but it didn't work.
new My_Featured_Image_Columns( array('team-member','challenge'), array() );
So I am guessing that 2 instantiations are necessary.
new My_Featured_Image_Columns( 'team-member', array() );
new My_Featured_Image_Columns( 'challenge', array() );
Thank you,
John.
Hi John,
You're right about 2 instantiations. Because the class is designed for single post type, we can't pass an array to its constructor. Initializing it twice for different post types does the job.
Hello - Thank you, as always, for the great help and documentation.
I attempted to use this function for adding the featured image to a CPT added via MetaBox.
The column simply does not show if I add any value to $position =
~David
MetaBox (Version 5.6.3)
MB Admin Columns (Version 1.6.0)
/* Add Featured Images to Admin Columns
* https://docs.metabox.io/extensions/mb-admin-columns/
*/
add_action( 'admin_init', 'prefix_add_custom_columns', 20 );
function prefix_add_custom_columns() {
class Prefix_Custom_Admin_Columns extends \MBAC\Post {
public function columns( $columns ) {
$columns = parent::columns( $columns );
$position = '';
$target = '';
$this->add( $columns, 'featured_image', 'Logo', $position, $target );
// Add more if you want
return $columns;
}
public function show( $column, $post_id ) {
switch ( $column ) {
case 'featured_image':
the_post_thumbnail( [40, 40] );
break;
// More columns
}
}
}
new Prefix_Custom_Admin_Columns( 'partner', array() );
}
David, your code is working great for me.
Thanks
Jochen