Run code on specific custom post types in WordPress admin

Sometimes, I want to run custom code on specific WordPress admin pages only. For example, let’s say I want to add a custom metabox to my ‘portfolio’ post edit screen, but only for that particular custom post type. I do not want this metabox to show up on my ‘posts’ or ‘pages’ edit screens. One way to achieve this is to use the ‘get_current_screen’ function and check that against the current screen you are on.

// CHECK IF CUSTOM POST TYPE IS PORTFOLIO
add_action( 'admin_head', 'kpry_if_cpt_is_portfolio' );
function kpry_if_cpt_is_portfolio() {

    // get the current screen and save into a variable
    $current_screen = get_current_screen();

    // check if the screen we are on is the desired post type
    if( $current_screen->post_type === 'portfolio' ) {
        // run your custom code here
    }
}