Lets say we are creating a plugin witch needs to load a javascript file on it’s settings page, we would only want to load the file on that specific page and not in every other admin page.

To do so, we can declare a global variable while creating the settings page so we can know exactly when we need to load our js file.

1. Create the settings page for the plugin.

 
function my_settings_page (){
 
     global $my_settings_page;
 
     $my_settings_page = add_options_page( __('My Settings', 'my-domain'), 
                                           __('Settings', 'my-domain'), 
	 			           'manage_options', 
                                           'my-page-slug', 
	 				   'my-callback'
	 				 );
}
 
add_action( 'admin_menu', 'my_settings_page');

2. Make the call checking the global variable $my_settings_page;

 
function my_admin_script( $hook ) {
 
    global $my_settings_page;
 
    if( $hook != $my_settings_page ) return;
 
    wp_enqueue_script( 'my-admin-script', MY_PLUGIN_URL . 'js/my-script.js');
}
 
add_action( 'admin_enqueue_scripts', 'my_admin_script' );
 
/*
To call the script in other WordPress pages, for example the edit page of a post: 
 
if( $hook != 'edit.php' ) return;
 
Other pages:
- Dashboard: index.php
- Media library: upload.php
- Comments: edit-comments.php
- Edit a comment: comment.php
- Appearance: themes.php
- Widgets: widgets.php
- Menus: nav-menus.php
- Plugins: plugins.php
- Users: users.php
- General Settings: options-general.php
*/

More information:
http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts

Load scripts only when needed in the WordPress admin
Tagged on:

Leave a Reply

Your email address will not be published. Required fields are marked *