How to enqueue scripts on custom post add/edit pages?

I’m trying to enqueue a JS script only when someone is adding or editing a custom post type I created called “recipes”. Currently the script works ok when I do this:

if (is_admin()){
    wp_enqueue_script( 'my-script' );
}

But this loads it in every admin page, I’m assuming I need to hook it to a function but I hvae no idea what it’d be.

Thanks in advance!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can do it like this (put in your functions.php) :

function add_admin_scripts( $hook ) {

    global $post;

    if ( $hook == 'post-new.php' || $hook == 'post.php' ) {
        if ( 'recipes' === $post->post_type ) {     
            wp_enqueue_script(  'myscript', get_stylesheet_directory_uri().'/js/myscript.js' );
        }
    }
}
add_action( 'admin_enqueue_scripts', 'add_admin_scripts', 10, 1 );

Method 2

There’s a hook for that, and it’s dead-simple to use. See this tutorial for an example implementation.

Edit

Justin moved his tutorials from DevPress to his personal site. Here’s the updated link for the tutorial.

Method 3

Rootstheme (which is based on Twitter Bootstrap) has a really elegant way of loading scripts depending on the page/post type as seen in the roots_scripts function which can be seen here on github.

Basically register all your scripts and styles then have conditional statements that wrap your wp_enqueue_script or wp_enqueue_style statements.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x