How to add CSS only to the options page of a plugin in WordPress?

I want to add a stylesheet for the options_page of my plugin only. But how to do that? My code so far:

function add_options_page_style() {
    wp_register_style('options_page_style', plugins_url('css/options_style.css',__FILE__));
    wp_enqueue_style('options_page_style');
}
add_action( 'admin_menu', 'add_options_page_style' );

I could place an if statement before the line with add_action... but I’m not sure how to filter my options page. I already tried the $pagename variable and also this line: $wp_query->queried_object->post_name; but it didn’t work.

Read More

The filter $_GET['page'] does work but might break in future versions.

Related posts

Leave a Reply

2 comments

  1. Somewhere you’ll be registering page like this:-

    function register_page(){
        global $page_hook_suffix;
        $page_hook_suffix = add_options_page('Your_plugin', 'Your_plugin', 'manage_options', __FILE__, 'display_form');
    }    
    add_action('admin_menu', 'register_page');
    

    And while enqueueing script you’ll do something like this:-

    function my_enqueue($hook) {
        global $page_hook_suffix;
        if( $hook != $page_hook_suffix )
            return;        
        wp_register_style('options_page_style', plugins_url('css/options_style.css',__FILE__));
        wp_enqueue_style('options_page_style');
    }
    add_action( 'admin_enqueue_scripts', 'my_enqueue' );
    
  2. function load_custom_wp_admin_style($hook) {
        // Load only on ?page=mypluginname
        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' );
    

    add your page slug as suffix to toplevel_page_
    e.g. if page slug is this-plugin-options
    then

    if($hook != 'toplevel_page_this-plugin-options') {
      return;
    }
    

    here is wordpress doc with
    Example: Load CSS File on All Admin Pages,
    Example: Load CSS File from a plugin on specific Admin Page