Advertisement
Tips

Quick Tip: Conditionally Including JS and CSS With get_current_screen

by

As many stated before me: "A good WordPress citizen only loads their files where they're needed". This principle applies both to front-end and back-end (admin). There's no justification for loading CSS and JS files on every admin page when you only need them on one single page you created. Thankfully doing things the right way is only one function call away.

"Never include CSS or JS files on all admin pages. It will cause conflicts with other plugins."


There's a WordPress Function for Everything

Since almost all admin pages have a unique URL it's really not difficult to detect when a certain page is loaded and then (and only then) include JS and CSS files we need. We can use $_SERVER['REQUEST_URI'], or in many cases, the $_GET['action'] variable. However there's a much easier, cleaner and more standardized way of doing that. Say hello to the get_current_screen function.

Things to know about the get_current_screen function:

  • It was introduced in WordPress v3.1, so if you try to use it in older versions you'll get a "call to undefined function" error. Using the function_exists function to check for it is a good idea if you want to provide an alternative.
  • It's not available in the admin_init or init hooks because it gets initialized after those hooks are called.
  • The function returns a WP_Screen object with a lot of info but you'll mainly be interested in the id object property.
  • It's not available on the front-end (because it serves no purpose there).

A Few Lines of Code Make All the Difference

Let's assume your plugin has an options page under the Settings menu which you created with:

add_options_page('My Plugin', 'My Plugin', 'manage_options', 'my_plugin', 'my_plugin_options');

You need some extra CSS and JavaScript on that page so you add this code as well:

// Bad code below! Don't copy/paste!
add_action('admin_enqueue_scripts', 'my_plugin_scripts');

function my_plugin_scripts() {
	wp_enqueue_style('farbtastic');
	wp_enqueue_script('farbtastic');
}

That's bad! Don't do that! The snippet above will include CSS and JS for Farbtastic color picker on every single admin page. If other plugins want to get rid of your includes on their pages they have to use wp_dequeue_* functions to dequeue them. That's really unnecessary and rude of us because we can write better code!


add_action('admin_enqueue_scripts', 'my_plugin_scripts');

function my_plugin_scripts() {
	// Include JS/CSS only if we're on our options page
	if (is_my_plugin_screen()) {
		wp_enqueue_style('farbtastic');
		wp_enqueue_script('farbtastic');
	}
}

// Check if we're on our options page
function is_my_plugin_screen() {
	$screen = get_current_screen();
	if (is_object($screen) && $screen->id == 'settings_page_my_plugin') {
		return true;
	} else {
		return false;
	}
}

It's Really Easy

If you have a look at our improved code you can see we only added one if statement and a simple function – is_my_plugin_screen which checks if we're on our plugin's options page. The variable $screen holds the WP_Screen object which has many properties but we're only interested in the id one. That id consists of a prefix "settings_page_", which is the same for all settings pages, and a string "my_plugin" which is unique to our plugin because we defined it as the 4th parameter in the add_options_page function call.

The code is very simple and easily adaptable to any admin screen. To see what the id is of the current screen simply dump the content of $screen with:

echo '<pre>' . print_r(get_current_screen(), true) . '</pre>';

Things to take home:

  • Never include CSS or JS files on all admin pages; it will cause conflicts with other plugins.
  • Use get_current_screen after init to find out when your admin screen is visible and only then include additional files.
  • You can find a list of the core admin screen IDs in the Codex under Admin Screen Reference.
  • Never echo <script> or <style> tags; always use wp_enqueue_* functions.
  • Check the Codex to see if the script you need is included in WP core already.
Related Posts
  • Code
    Articles
    WordPress Initialization Hooks: Benefits and Common MistakesHooks
    In programming, initialization of data is important as it's where we setup the prerequisites for the application such as its attributes, its required files and data, its connection to the database, and so on. WordPress itself has a well-defined initialization procedure. Through the page life cycle, WordPress fires a number of actions many of which we've covered in previous articles. To that end, it provides a set of initialization hooks which are naturally used to initialize the application before executing its primary functionality. As plugin and theme developers, it's important to understand the use cases and common mistakes of these initialization hooks, in order to build quality applications. In this article, we are going to take a look at the importance of WordPress initialization hooks and how they are used in various scenarios.Read More…
  • Code
    Plugins
    Using HighCharts in WP-AdminHighcharts 400
    Charts are a great way to present data. They make data more digestible by making it visually appealing. In WordPress, there is no built-in method for getting posts and pages data in a graphical form. Although, there are certain plugins available which integrate Google Analytics with WordPress, but they are overkill if you want to get only a portion of that data. Also, nothing should keep you from learning new techniques and to dive straight into the subject is the best way to learn.Read More…
  • Code
    Creative Coding
    Customizing the WordPress Admin - Listings ScreensCustomize wordpress admin rachel 400
    In Parts 1-4 of this series I showed you how to: Customize the WordPress login screen Customize the dashboard Customize the admin menu Add help text to post editing screens In this fifth instalment I'll show you how to customize listings screens in the admin.Read More…
  • Code
    Theme Development
    How to Integrate Bootstrap Navbar Into WordPress ThemeBootstrapd 400
    Have you ever wanted to speed-up the process of theme development? I assume the answer is "yes" and you already know about Bootstrap and use it in mock-ups for development. This raises the question: "How can you integrate Bootstrap components into a WordPress theme?"Read More…
  • Code
    Cheat Sheets
    The Complete Guide to Proper JavaScript Usage With WordPressJavascript 400
    I remember thinking "What the heck do we need JavaScript for, when we have Flash?" when I was fourteen. Although I still remember how I enjoyed coding stuff with ActionScript 2.0 back then, I saw how much one can achieve with JavaScript and fell in love with it. I'm not an expert on JavaScript (yet) but I can say I'm over and done with Flash for a long time. When it comes to WordPress, the biggest blogging platform and content management system worldwide, JavaScript is - of course - very useful for many things: content sliders, lightbox galleries, slick shopping carts, UI elements like tabs or accordions... you name it. But how exactly should we use JavaScript with WordPress? Returning or echoing a bunch of HTML script elements is one way to do it - and it's wrong. In this tutorial, we're going to see how to enqueue JavaScript files inside our pages and how to pass translatable data to the JavaScript code.Read More…
  • Code
    Plugins
    A Better Forum List Widget for bbPressBbpress
    When bbPress was still a standalone installation, I had tried it out and wasn't really impressed. Things were clunky and it didn't always work the way it was supposed to. After languishing for a few years, Automattic decided to take bbpress and turn it into a plugin, improving the functionality leaps and bounds and making it a strong contender amongst other forum option for WordPress.Read More…