Using WordPress ‘get_current_screen()’ PHP function

The get_current_screen() WordPress PHP function retrieves the current screen object in the admin dashboard.

Usage

$current_screen = get_current_screen();

Parameters

  • None

More information

See WordPress Developer Resources: get_current_screen()

Examples

Run code on the admin widgets page

This code will run only on the admin widgets page:

add_action('current_screen', 'wpdocs_this_screen');

function wpdocs_this_screen() {
    $currentScreen = get_current_screen();
    if($currentScreen->id === "widgets") {
        // Run some code, only on the admin widgets page
    }
}

Redirect the admin dashboard to a custom page

This code will redirect the admin dashboard to a custom page:

add_action('current_screen', 'wpdocs_custom_redirect_admin_dashboard');

function wpdocs_custom_redirect_admin_dashboard() {
    if (is_admin()) {
        $my_current_screen = get_current_screen();
        if (isset($my_current_screen->base) && 'dashboard' === $my_current_screen->base) {
            wp_redirect(admin_url().'?page=custom_dashboard');
            exit();
        }
    }
}

Check if the function exists before using it

This code checks if the get_current_screen() function exists before using it:

if (function_exists('get_current_screen')) {
    $current_screen = get_current_screen();
    // Do your thing
}

Add contextual help to an admin page

This code adds contextual help to an admin page with the slug my_admin_page:

add_action('admin_menu', 'wpdocs_admin_add_page');

function wpdocs_admin_add_page() {
    global $wpdocs_admin_page;
    $wpdocs_admin_page = add_options_page(__('Wpdocs Admin Page', 'wpdocs_textdomain'), __('Wpdocs Admin Page', 'wpdocs_textdomain'), 'manage_options', 'wpdocs_textdomain', 'wpdocs_admin_page');
    add_action('load-'.$wpdocs_admin_page, 'wpdocs_admin_add_help_tab');
}

function wpdocs_admin_add_help_tab() {
    global $wpdocs_admin_page;
    $screen = get_current_screen();

    if ($screen->id != $wpdocs_admin_page) return;

    $screen->add_help_tab(array(
        'id' => 'wpdocs_help_tab',
        'title' => __('Wpdocs Help Tab'),
        'content' => '<p>' . __('Descriptive content that will show in Wpdocs Help Tab body goes here.', 'wpdocs_textdomain') . '</p>',
    ));
}

Check the custom post type on the current screen

This code checks if the custom post type of the current screen is wpcrm-contact:

add_action('trashed_post', 'trash_wpcrm_contact');

function trash_wpcrm_contact($post_id){
    $screen = get_current_screen();
    if('wpcrm-contact' != $screen->post_type){
        // This is not our custom post, so let's exit
        return;
    }
    // ...
}