I'd like to enqueue scripts only for an admin page that I've created.

There's an example of this here: http://codex.wordpress.org/Function_Reference/wp_enqueue_script#Load_scripts_only_on_plugin_pages

But it's not working for me, I think because I'm writing my plugin within a class. add_action only works with in the constructor??

Is there a way to add scripts to a specific page from within a class?

I came up with this method: My main plugin page is a list of custom post types (if you set 'show_in_menu' => 'custom_page_slug' in the post type args it takes over that page with a list of posts). When I created the post type, I set a variable up with the post type name:

$args = register_post_type('post-type', $args );
$this->posttype = $args->name;

Then this call in the constructor:

add_action( 'admin_print_scripts', array( &$this, 'scripts_init' ) );

And this in the scripts_init function:

global $current_screen;    
if( $current_screen->id == $this->posttype )
wp_enqueue_script( ... );

It works. But it seems more complicated than it needs to be. Is there a better way to accomplish this?


1 Answer 1


Instead of hooking into admin_print_scripts only, you should hook into your specific page slug which is appended to admin_print_scripts-. (note trailing hyphen). The reference page you linked to shows this, but you seem to be omitting the $page concatenation to admin_print_scripts-.


$page = add_theme_page( 'Options', 'Options', 'edit_theme_options', 'options-panel', 'topf_admin_options_markup' );

add_action( "admin_print_scripts-$page", 'enqueue_my_admin_scripts' );

I'm using the slug $page returned from add_theme_page; you should provide your own slug. Scripts will only be loaded for your specific page and there is no need to check within your enqueue function.

  • That's not working. The add_action has to be within the __construct to work. Even if I set up a class variable then try to access it: add_action( 'admin_print_scripts-'.$this->pagename, 'scripts_init' ), it doesn't work. Its like the variable is not set yet. Maybe it has something to do with the order in which the action hooks fire? Jun 12, 2011 at 13:14
  • The add_action does not have to be in the __construct. It should be where ever you are creating your page. eg: class ControlPanel { function __construct() { add_action( 'admin_menu', array( &$this , 'my_admin_menu' )); } function my_admin_menu() { $page = add_theme_page('DTI Options', 'DTI Options', 'edit_theme_options', "diverge_theme_options", array( &$this , 'optionspage' )); add_action( "admin_print_scripts-$page", array( &$this , 'scripts_init' )); } }
    – Jeff
    Jun 12, 2011 at 15:09

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.