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:
Property | Description |
---|---|
id | The unique ID of the screen |
base | The 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. |
action | Any action associated with the screen. add for *-add.php and *-new.php screens. Empty otherwise. |
is_network | Whether the screen is in the network (multisite) admin. |
is_user | Whether the screen is in the user admin. |
parent_file | 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 . |
parent_base | 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 . |
post_type | The 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 . |
taxonomy | The 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'] );
}
} );
Leave a Reply