avatar Deluxe Blog Tips About Projects

Getting current admin screen info in WordPress

There're a couple of variables can help us determining which admin screen we're seeing: $pagenow for current page ID, $typenow for current post type, etc. But using these variables requires us a huge afford to combine them just to get the correct information we want. Fortunately, WordPress gives us a more completed solution with WP_Screen class which turns out the best way to get current admin screen information with ease of use.

How to get the current admin screen info?

To get the current screen object, simply use:

$screen = get_current_screen();

This $screen is an instance of WP_Screen class, which has the following public properties:

idThe unique ID of the screen
baseThe base type of the screen. This is typically the same as $screen->id but with any post types and taxonomies stripped. For example, the base of post.php or post-new.php is post for all post types.
actionAny action associated with the screen. add for *-add.php and *-new.php screens. Empty otherwise.
is_networkWhether the screen is in the network (multisite) admin.
is_userWhether the screen is in the user admin.
parent_fileThe 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.
parent_baseThe 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.
post_typeThe post type associated with the screen, if any. For example:
The edit.php?post_type=page screen has a post type of page.
The edit-tags.php?taxonomy=$taxonomy&post_type=page screen has a post type of page.
taxonomyThe taxonomy associated with the screen, if any. For example, the edit-tags.php?taxonomy=category screen has a taxonomy of category.

Enqueue scripts and styles for admin pages

A typical use of the screen object is enqueuing scripts and styles for admin pages. We can use its properties to check whether we're on the page and prevent enqueuing files for other admin pages.

add_action( 'admin_enqueue_scripts', function() {
    $screen = get_current_screen();

    if ( 'post' === $screen->base && 'slider' === $screen->post_type ) {
        wp_enqueue_script( 'slider-options', get_stylesheet_directory_uri() . '/js/slider-option.js', ['jquery'] );
} );

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com