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?
Thanks!
Instead of hooking into
admin_print_scripts
only, you should hook into your specific page slug which is appended toadmin_print_scripts-
. (note trailing hyphen). The reference page you linked to shows this, but you seem to be omitting the$page
concatenation toadmin_print_scripts-
.eg:
I’m using the slug
$page
returned fromadd_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.