Blog

Loading CSS and JS for admin pages

By:
on:

When building your own WordPress plugin or theme you will often want to load your own css or javascript files.

This is simple in WordPress, you just use a hook where you register and enqueue your style or script...

But what if you wanted your styles or scripts only to load on specific admin pages that you added?

What hook should you use?

You won't find that in the list of action and filter hooks in the WordPress Codex since the slug for your page is something you wrote...

Luckily WordPress returns a page hook suffix when you add an admin page or a submenu page.

Simply put that in a variable, and you can add the correct hook to your add_action call.

Example:

$page = add_submenu_page(

    'as_example',

    'Example for Loading styles and script for admin pages',

    'Example',

    'manage_options',

    'as_example_menu_slug',

    'function_to_output_page_name_as_string'

);



add_action( 'admin_print_styles-' . $page, 'as_enqueue_styles' );

add_action( 'admin_print_scripts-' . $page, 'as_enqueue_scripts' );



function as_enqueue_styles() {

    wp_enqueue_style( 'as_example_page_style' );

}



function as_enqueue_scripts() {

    wp_enqueue_script( 'as_example_page_script' );

}



function as_register_styles(){

        wp_register_style( 'as_example_page_style', plugins_url('admin.css', __DIR__ . '/../../css/admin.css') );

}



add_action('admin_init', 'as_register_styles' );



function as_register_scripts(){

        wp_register_script( 'as_example_page_script', plugins_url('admin.js', __DIR__ . '/../../js/admin.js') );

}



add_action('admin_init', 'as_register_scripts' );

KOEN IS HAPPY TO INTRODUCE APPSALOON
APPSALOON BV
Bampslaan 21 box 3.01
3500 Hasselt
Belgium
VAT: BE08 4029 5063
2021 © AppSaloon All Rights Reserved
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram