How to use hook admin_init for add_action for custom post type column

I'm adding a post thumbnail column to the edit custom post screen. The post thumbnails are showing up fine however I would like to hook it with admin_init to take some load off the website.

This is my code for adding the thumbnail's to my edit custom post screen:

add_filter( 'manage_edit-model_columns', 'my_columns_filter', 10, 1 );
function my_columns_filter( $columns ) {
$column_thumbnail = array( 'thumbnail' = 'Thumbnail' );

$columns = array_slice( $columns, 0, 1, true ) + $column_thumbnail + array_slice(  $columns, 1, NULL, true );

return $columns;
}


add_action( 'manage_model_posts_custom_column', 'my_column_action', 10, 1 );
function my_column_action( $column ) {
global $post;
switch ( $column ) {
    case 'thumbnail':
        echo get_the_post_thumbnail( $post-ID, 'edit-screen-thumbnail' );
        break;
    }
}

Could someone explain (show me how) to use the admin_init hook for my thumbnail column code? Thanks.

Topic admin-init customization Wordpress

Category Web


Hooking this into admin_init will ensure that the code only runs in the admin panel, but it's not the proper way to do so as it prevents other plugins from accessing the new column before that hook. You could simply use is_admin() to determine whether the current page is an admin page.

if ( is_admin() ) {
    add_filter( 'manage_edit-model_columns', 'my_columns_filter', 10, 1 );
    function my_columns_filter( $columns ) {
    $column_thumbnail = array( 'thumbnail' => 'Thumbnail' );

    $columns = array_slice( $columns, 0, 1, true ) + $column_thumbnail + array_slice(  $columns, 1, NULL, true );

    return $columns;
    }


    add_action( 'manage_model_posts_custom_column', 'my_column_action', 10, 1 );
    function my_column_action( $column ) {
    global $post;
    switch ( $column ) {
        case 'thumbnail':
            echo get_the_post_thumbnail( $post->ID, 'edit-screen-thumbnail' );
            break;
        }
    }
}

However, doing this won't take any significant load off your website. add_filter and add_action are very, very inexpensive functions.

You can also leave this kind of functionality to a plugin (such as Admin Columns).

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.