Include admin scripts/styles in WordPress plugin

There are two ways of including custom scripts/styles in an admin page for a WordPress 3 plugin.

Solution 1 (Deprecated):


$slug = add_submenu_page('myplugin.php', 'My Plugin', 'My Plugin', 'upload_files', __FILE__, 'myplugin_options');

add_action('admin_print_scripts-'. $slug, 'myplugin_enqueue_admin_scripts');
add_action('admin_print_styles-'. $slug, 'myplugin_enqueue_admin_styles');

function myplugin_enqueue_admin_scripts($suffix) {
	$plugin_path = plugin_dir_url(__FILE__) . 'resources/';
	wp_enqueue_script('jquery.js', $plugin_path . 'jquery.pack.js');
}

function myplugin_enqueue_admin_styles($suffix) {
	$plugin_path = plugin_dir_url(__FILE__) . 'resources/';
	wp_enqueue_style('jquery.css', $plugin_path . 'jquery.css');
}

Solution 2 (recommended):

$slug = add_submenu_page('myplugin.php', 'My Plugin', 'My Plugin', 'upload_files', __FILE__, 'myplugin_options');

add_action('admin_enqueue_scripts', 'myplugin_enqueue_admin_scripts');


function myplugin_enqueue_admin_scripts($hook_suffix) {
	if ($hook_suffix == 'myplugin/slug') {
		$plugin_path = plugin_dir_url(__FILE__) . 'resources/';
		wp_enqueue_script('jquery.js', $plugin_path . 'jquery.pack.js');
		wp_enqueue_style('jquery.css', $plugin_path . 'jquery.css');
	}
}

Leave a Reply

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