Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers 2

up vote 2 down vote accepted

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
share|improve this answer
    
I'd personally have put the conditional logic into the callback, aside from that i agree with the choice of hook. :) –  t31os Apr 25 '13 at 17:10
    
@t31os Why make the parser travel further than necessary? ;) And also, you'd add an action that does not do anything for most of the pages/time. –  t f Apr 25 '13 at 17:12
    
Correct, but it looks prettier. The runtime difference should be pretty negligible to. –  t31os Apr 25 '13 at 17:16
    
Chosen as the answer. Though the one above seems like it would work as well. I ended up figuring this out on my own but what you suggested is basically what I did. –  dcp3450 Apr 30 '13 at 19:23
add comment

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;
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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