How do I only load js on the post-new.php and post.php pages in admin?

I have some script that is loading in the admin. I only need it to load on the new post and edit posts screens.

What is the best way to do this?

Related posts

Leave a Reply

2 comments

  1. Check the page and enqueue your script accordingly:

    global $pagenow;
    if (! empty($pagenow) && ('post-new.php' === $pagenow || 'post.php' === $pagenow ))
        add_action('admin_enqueue_scripts', 'enqueue_my_scripts');
    
    function enqueue_my_scripts() {
        wp_enqueue_script(...);
    } // function enqueue_my_scripts
    
  2. The global variable $hook_suffix is:

    • post-new.php for the new post and
    • post.php for the regular post editor

    In wp-admin/admin-header.php there are some special hooks:

    do_action('admin_enqueue_scripts', $hook_suffix);
    do_action("admin_print_styles-$hook_suffix");
    do_action('admin_print_styles');
    do_action("admin_print_scripts-$hook_suffix");
    do_action('admin_print_scripts');
    do_action("admin_head-$hook_suffix");
    do_action('admin_head');
    

    So you can use admin_print_styles-$hook_suffix, in your cases:

    add_action( 'admin_print_scripts-post-new.php', 'your_prefix_enqueue_scripts' );
    add_action( 'admin_print_scripts-post.php',     'your_prefix_enqueue_scripts' );
    

    To find the correct $hook_suffix for any admin page use something like this:

    add_action( 'admin_footer', 'print_hook_suffix' );
    
    function print_hook_suffix()
    {
        global $hook_suffix;
    
        print '$hook_suffix: ' . $hook_suffix;
    }