3

I am learning about Wordpress, and i want to load custom CSS for a specific admin page of my plugin. I read at Wordpress Plugin API and do something like this:

//I ADD MY OPTION PAGES
add_action( 'admin_menu', 'my_plugin_menu' );
function my_plugin_menu() {
    add_menu_page( 'My option page', 'My plugin', 'manage_options', 'my-fist-slug', 'my_first_func', 'dashicons-star-empty');
    add_submenu_page('my-fist-slug', 'General Setting', 'General', 'manage_options', 'my-fist-slug', 'my_first_func');
    add_submenu_page('my-fist-slug'', 'Some else options', 'Some options', 'manage_options', 'my-second-slug', 'my_second_func');
}

I just want to load my CSS only for my option pages, then i do this:

add_action('admin_enqueue_scripts', 'ln_reg_css_and_js');
function ln_reg_css_and_js($hook)
{
    if($hook != 'my-first-slug'){
        return;
    }

    wp_enqueue_style('boot_css', plugins_url('inc/bootstrap.css',__FILE__ ));
    wp_enqueue_script('boot_js', plugins_url('inc/bootstrap.js',__FILE__ ));
    wp_enqueue_script('ln_script', plugins_url('inc/main_script.js', __FILE__), ['jquery'], false, true);
}

This has same codes like the WP codex. But, i don't know how to define $hook, and the result is my custom css was not loaded. Anyone can teaches me how to do this?

1

3 Answers 3

7
add_action('admin_enqueue_scripts', 'ln_reg_css_and_js');

    function ln_reg_css_and_js($hook)
    {

    $current_screen = get_current_screen();

    if ( strpos($current_screen->base, 'my-fist-slug') === false) {
        return;
    } else {

        wp_enqueue_style('boot_css', plugins_url('inc/bootstrap.css',__FILE__ ));
        wp_enqueue_script('boot_js', plugins_url('inc/bootstrap.js',__FILE__ ));
        wp_enqueue_script('ln_script', plugins_url('inc/main_script.js', __FILE__), ['jquery'], false, true);
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

4

You can also include the CSS on specific plugin page as well :)

//Enqueue Admin CSS on Job Board Settings page only
if ( isset( $_GET['page'] ) && $_GET['page'] == 'job-board-settings' ) {
    // Enqueue Core Admin Styles
    wp_enqueue_style( simple_job_board, plugin_dir_url( __FILE__ ) . 'css/simple-job-board-admin.css');
    }

Comments

3
function load_custom_wp_admin_style($hook) {
        // $hook is string value given add_menu_page function.
        if($hook != 'toplevel_page_mypluginname') {
                return;
        }
        wp_enqueue_style( 'custom_wp_admin_css', plugins_url('admin-style.css', __FILE__) );
}
add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' );

For more see: Codex examples

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.