Loading scripts, CSS and jQuery, within a plugin for use on admin pages is one of the most common areas that developers make mistakes. If you plugin’s administrative pages require any scripts that are not already loaded in WordPress by default, you should always ensure that those scripts are only loaded on your plugin’s page, and not on every other page inside of the WordPress dashboard.

Limiting your scripts loads to specific pages is really pretty simple.

1
2
3
4
5
6
7
8
9
10
11
12
function your_plugin_admin_styles() 
{
        // this is a variable that holds the path to your plugin folder, defined outside of this function
	global $plugin_base_dir;	
	wp_enqueue_style('your-plugin-admin', $plugin_base_dir . 'includes/css/admin-styles.css');
}
// load the scripts on only the plugin admin page 
if (isset($_GET['page']) && ($_GET['page'] == 'your-plugin-folder/your-plugin-file.php')) 
{ 
        // if we are on the plugin page, enable the script
	add_action('admin_print_styles', your_plugin_admin_styles');
}

I have given you a simple example enqueuing only one CSS file, but you can easily add as many scripts as you need.

Loading your scripts in this manner is very important because it helps to mitigate the possibility of conflicts with other plugins. It also helps to increase page loading times within the dashboard. If each admin page has to load the scripts for every plugin active, you are going to experience much delayed loading time.

  1. Mark

    This awesome! I’ve been having trouble with this recently. Is adding a script to the front end via a plugin such as nivoslider done in a similar way? I tried a myriad of tuts on that subject and it all ended in failure.

    Thanks!

    • pippin

      Yes, this is almost exactly how it would be done. The only difference is the hook that is used. Instead of add_action(‘admin_print_scripts’, your_plugin_admin_styles’);, you would use add_action(‘wp_print_scripts’, your_plugin_admin_styles’);

  2. diljan

    hi pippin

    you forgott one litle thing on line 11 🙂

    instead of:
    add_action(‘admin_print_styles’, your_plugin_admin_styles’);

    change to:
    add_action(‘admin_print_styles’, ‘your_plugin_admin_styles’);

    the ” ‘ ” in the action, before ” your_plugin_admin_styles’); “

Comments are closed.