Adding Scripts in the Admin Area

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

Read More

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?

Thanks!

Related posts

Leave a Reply

1 comment

  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-.

    eg:

    $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.