函数文档

get_current_screen()

💡 云策文档标注

概述

get_current_screen() 函数用于获取当前 WordPress 后台屏幕的 WP_Screen 对象,返回该对象或 null(当屏幕未定义时)。开发者可利用此函数在特定管理页面执行条件代码。

关键要点

  • 返回类型为 WP_Screen|null,若未设置全局变量 $current_screen 则返回 null。
  • 函数在 admin_init 钩子之后才可用,使用前应检查函数是否存在或确保在 current_screen 钩子或之后调用。
  • WP_Screen 对象包含 id、base、post_type 等属性,可用于识别当前屏幕(如 'dashboard'、'post')。
  • 主要用于后台管理,前台无效。

代码示例

// 检查函数是否存在并获取当前屏幕
if ( function_exists( 'get_current_screen' ) ) {
    $current_screen = get_current_screen();
    if ( 'dashboard' === $current_screen->base ) {
        // 在仪表盘执行代码
    }
}

注意事项

  • 避免在 admin_init 之前调用,否则可能返回不完整的对象或 null。
  • 使用 set_current_screen() 手动设置屏幕可能不会正确填充属性,建议依赖系统自动设置。

📄 原文内容

Get the current screen object

Return

WP_Screen|null Current screen object or null when screen not defined.

Source

function get_current_screen() {
	global $current_screen;

	if ( ! isset( $current_screen ) ) {
		return null;
	}

	return $current_screen;
}

Changelog

Version Description
3.1.0 Introduced.

User Contributed Notes

  1. Skip to note 11 content

    PAGE               $SCREEN_ID           FILE
    -----------------  -------------------  -----------------------
    Media Library      upload               upload.php
    Comments           edit-comments        edit-comments.php
    Tags               edit-post_tag        edit-tags.php
    Plugins            plugins              plugins.php
    Links              link-manager         link-manager.php
    Users              users                users.php
    Posts              edit-post            edit.php
    Pages              edit-page            edit.php
    Edit Site: Themes  site-themes-network  network/site-themes.php
    Themes             themes-network       network/themes
    Users              users-network        network/users
    Edit Site: Users   site-users-network   network/site-users
    Sites              sites-network        network/sites

  2. Skip to note 12 content

    Be aware the this function doesn’t always exist, something that @ravanh had sort of eluded to. It isn’t loaded and available until after admin_init has fired. It is advisable to check whether the function exists when using it within any hooks in the even those hooks fire before that function is actually loaded and available to use.

        /**
         * Check whether the get_current_screen function exists
         * because it is loaded only after 'admin_init' hook.
         */
        if ( function_exists( 'get_current_screen' ) ) {
            $current_screen = get_current_screen();
            // Do your thing.
        }

  3. Skip to note 14 content

    I was trying to find out the name of the admin dashboard.
    You can find out the current screen name by dumping it:

    $my_current_screen = get_current_screen();
    var_dump( $my_current_screen->base );

    Using this, I found the dashboard screen is just called ‘dashboard’ 🤯, so I could then redirect to a different page like this:

    /**
     * Redirect specific admin 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();
            }
        }
    }

  4. Skip to note 15 content

    The fields returned are:

    id (string) The unique ID of the screen
    action (string) Any action associated with the screen. ‘add’ for *-new.php screens. Empty otherwise.
    base (string) The base type of the screen. For example, for a page ‘post-new.php’ the base is ‘post’.
    parent_base (string) The base menu parent. This is derived from $parent_file by removing the query string and any .php extension. For example, parent_file values of ‘edit.php?post_type=page’ and ‘edit.php?post_type=post’ have a parent_base of ‘edit’
    parent_file (string) The parent_file for the screen per the admin menu system. Some parent_file values are ‘edit.php?post_type=page’, ‘edit.php’, and ‘options-general.php’
    post_type (string) The post type associated with the screen, if any. For example, the ‘edit.php?post_type=page’ screen has a post type of ‘page’
    taxonomy (string) The taxonomy associated with the screen, if any. For example, the ‘edit-tags.php?taxonomy=category’ screen has a taxonomy of ‘category’

    Returned object:

    WP_Screen Object
    (
        [action] => 
        [base] => post
        [id] => post
        [is_network] => 
        [is_user] => 
        [parent_base] => edit
        [parent_file] => edit.php
        [post_type] => post
        [taxonomy] => 
        ...
        (private fields)
    )

  5. Skip to note 16 content

    Be aware that at the global $current_screen gets set relatively late, right after the admin_init has run. This is done with function set_current_screen() in template files like admin-header.php and admin.php or when processing admin ajax requests.

    Calling set_current_screen() yourself earlier will not help. Although get_current_screen() does not return null anymore, the current screen object will not be populated with the correct properties, like get_current_screen()->$id, to work with.

    Use get_current_screen() at the current_screen hook or later.

  6. Skip to note 18 content

    This can be useful for conditionally executing code depending on which admin screen is currently being viewed.

    // Hook into the admin_head action to run your code in the admin area
    add_action( 'admin_head', 'wpdocs_admin_code' );
    
    function wpdocs_admin_code() {
        // Get the current screen object
        $current_screen = get_current_screen();
    
        // Check if the current screen is the dashboard
        if ( 'dashboard' === $current_screen->id ) {
            // Execute your code for the dashboard screen
            echo 'alert( "You are on the dashboard!" );';
        }
    
        // Check if the current screen is a post editing screen
        if ( 'post' === $current_screen->base ) {
            // Execute your code for the post editing screen
            echo 'alert( "You are editing a post!" );';
        }
    
        // Check for other screen IDs or bases as needed
        // For example, to check if it's a page editing screen:
        if ( 'page' === $current_screen->id ) {
            // Execute your code for the page editing screen
            echo 'alert( "You are editing a page!" );';
        }
    
        // More conditions can be added as needed
    }

  7. Skip to note 19 content

    Default Usage
    This example shows how you would add contextual help to an admin page you’ve created with the add_options_page() function. Here, we assume that your admin page has a slug of my_admin_page and exists under the Options tab.

    The get_current_screen() function is used in this example.

    id != $wpdocs_admin_page )
            return;
    
        // Add my_help_tab if current screen is My Admin Page
        $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>',
        ) );
    }
    ?>

  8. Skip to note 20 content

    This function is useful to figure out which screen you’re on in the Dashboard,

    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;
        }
        ....
    }

    Another useful attribute of the WP_Screen object returned by this function is the $screen->base attribute which is set to 'post' for any custom post edit screen, and is set to 'edit' for the custom post admin table page, which is very handy when loading custom css/scripts for additional function on those pages.