Add Scripts/Styles to Specific WordPress Admin Pages

We ran across an issue while creating a WordPress plugin. We needed a CSS stylesheet and a JS file to be included on a WordPress plugin Settings page but not on any other WordPress Admin page. In order to do this, we had to tap into the admin_print_styles- action. You need to add the page’s hook suffix to the end when you add the action in your plugin or theme. You can learn more about this action at https://developer.wordpress.org/reference/hooks/admin_print_styles-hook_suffix/.

Step 1: Add Action

When you create a menu or submenu page for your WordPress plugin or WordPress theme, you need to run add_action specifically related to the submenu.

$submenu = add_submenu_page( $plugin_name, 'Plugin Settings', 'Settings', 'administrator', $plugin_name.'-settings', 'display_plugin_admin_settings' );

add_action( 'admin_print_styles-' . $submenu,  'admin_settings_enqueue_styles');

add_action( 'admin_print_scripts-' . $submenu,  'admin_settings_enqueue_scripts');

Step 2: Add Admin Scripts Function

public function admin_settings_enqueue_scripts() {
     wp_enqueue_script( $plugin_name.'-example-js', '//www.wplauncher.com/js/example.js', array( 'jquery' ), $version, false );
}
	

Step 3: Add Admin Styles Function

public function admin_settings_enqueue_styles() {
     wp_enqueue_style( $plugin_name.'-example-css', '//www.wplauncher.com/css/example.css', array(), $version, 'all' );
}

Leave a Reply

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