Wordpress: Load custom CSS for specific plugin adm

2019-09-16 19:35发布

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?

标签: wordpress
3条回答
贼婆χ
2楼-- · 2019-09-16 19:47

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');
    }
查看更多
迷人小祖宗
3楼-- · 2019-09-16 19:57
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

查看更多
地球回转人心会变
4楼-- · 2019-09-16 19:59
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);
        }
    }
查看更多
登录 后发表回答