Try Tuts+ Premium, Get Cash Back!
Quick Tip: Conditionally Including JS and CSS With get_current_screen

Quick Tip: Conditionally Including JS and CSS With get_current_screen

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.
Gordan Orlic is WebFactory on Codecanyon
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • prathap

    very useful :)

    • http://www.webfactoryltd.com/ Gordan Orlic
      Author

      Glad to hear that!

  • Pingback: How to conditionally load CSS and JS in WordPress | WPAOT

  • http://miravalledesigns.com Patrick Miravalle

    This is definitely useful without a doubt, but how would you insert the CSS / JS if the user didn’t have WordPress 3.1 or higher?

    • http://www.webfactoryltd.com/ Gordan Orlic
      Author

      I always recommend using the enqueue functions. The other part of the job is testing when to actually do the include. You can use a method I mentioned (with $_SERVER['REQUEST_URI']), or the one with per-page hooks others mentioned in comments.

  • http://www.innovativephp.com/tutorials Rakhitha Nimesh

    Very interesting and useful article. I was used to do the same mistake and found out that it was wrong. This article explains the criteria which this can be used.

    Thanks for sharing Gordan. Keep posting interesting stuff on wordpress like this.

    • http://www.webfactoryltd.com/ Gordan Orlic
      Author

      You’re welcome! A few other quick tips will be up soon :)

  • http://codecanyon.net/user/cosmocoder CosmoCoder

    It was nice to know of this technique. However I would like to point out a much easier way to conditionally load scripts in the admin pages and that is by using the load-(page) hook. This hook allows us to attach any action/function when a particular admin page loads. It is explained here in the WP Codex – https://codex.wordpress.org/Plugin_API/Action_Reference/load-%28page%29

    So in this case the plugin js/css files would be loaded like this:

    $my_plugin_page = add_options_page(‘My Plugin’, ‘My Plugin’, ‘manage_options’, ‘my_plugin’, ‘my_plugin_options’);

    add_action(‘load-’.$my_plugin_page, ‘my_plugin_scripts’);

    function my_plugin_scripts(){
    // enqueue your scripts in this function
    }

    Hope that was useful.

    • http://www.webfactoryltd.com/ Gordan Orlic
      Author

      Nice method! I just hope people will stop including their stuff on all pages :) It’s really not that hard.

  • http://www.deluxeblogtips.com Rilwis

    There’s another way to enqueue scripts and styles for exact admin pages, using wp_print_style-{$page_hook}.

    By the way, there’re many information of the screen object that can be used to determine which admin page we’re on.

    • http://www.webfactoryltd.com/ Gordan Orlic
      Author

      True, I think we’ll se a lot more on the WP_Screen object in the upcoming WP versions.

  • http://amrabdelaziz.com amrabdelaziz

    Very distinct tut :
    thnx so much

    • http://www.webfactoryltd.com/ Gordan Orlic
      Author

      You’re welcome :)

  • http://bretglassett.com BretJG

    Perfect timing, was just needing to search for this for a project. Thanks!

  • http://www.customicondesign.com CUSTOM ICON DESIGN

    I love the article like this. when I have read the article, I ask myself why this guy know this, and I dont know? haha.

  • Pingback: WordPress Weekly Links | WPStream.com

  • Mihael

    Awesome and informative article as always. Thank you.

  • Pingback: » Inkludera JS och CSS med get_current_screen » Kim Bjurling

  • Pingback: Quick Tip: Conditionally Including JS and CSS With get_current_screen | Wptuts+ | | mayoWebmayoWeb

  • http://meta-blogger.com Michael Hall

    Nice tutorial. Personally i prefer to use request uri or sometimes i put conditional code right in the single.php template to determine which page or category id is active.

    It’s nice to have this method but if it only works for the admin, i’d probably stick with request uri since it is a little more versatile.

    it would be nice if you expanded on why not to do the things that you advise against like not echoing out script or css tags and why wp_enqueu is preferred, as some of us do not know why and tend to stick to old habits, but knowing why to and why not goes along way to circumventing this behavior and also helps to make your article a little longer and thorough.

    wordpress has so much to offer and so many updates that it is hard to keep on top of what’s considered best practice, but i’ll surely be following along here at wp.tutsplus.com

    thanks again for the great info.

  • Pingback: Tweet-Parade (no.20 May 2012) | gonzoblog.nl

  • http://www.twitter.com/brandongcarroll Brandon Carroll

    Thanks for the great tutorial! I’ve been wondering about how to do this in WordPress for the last few days.

  • Pingback: Best of Tuts+ in May 2012 - Milk-Break

  • Pingback: Best of Tuts+ in May 2012 | DigitalMofo

  • Pingback: Best of Tuts+ in May 2012

  • Pingback: Best of Tuts+ in May 2012 | My Creative Directory

  • Pingback: Best of Tuts+ in May 2012 | Shadowtek Hosting and Design Solutions

  • Pingback: » Best of Tuts+ in May 2012 TNR Today

  • Pingback: How to do damn near anything with WordPress – Stephanie Leary