Loading scripts to the Post Edit page only

I have added a few meta boxes for the posts and pages, so I want to load a js script only on the Create/Edit post and page. How can I do that?
Currently I’m using following but that loads the scripts in all pages in the admin.

function my_meta_boxes() {
    add_meta_box("post_meta", "Meta", "post_meta", "post", "normal", "high");
    add_meta_box("post_meta", "Meta", "post_meta", "page", "normal", "high");

}
add_action( 'add_meta_boxes', 'my_meta_boxes' );

function register_custom_scripts() {
    wp_enqueue_script( 'custom_js', get_template_directory_uri() . '/inc/meta/custom.js', array( 'jquery' ));
    wp_enqueue_style( 'custom_css', get_template_directory_uri() . '/inc/meta/custom.css');
}
add_action( 'admin_init', 'register_custom_scripts' );

Related posts

3 comments

  1. We can improve a little bit with :

    function specific_enqueue($hook_suffix) {
       if( 'post.php' == $hook_suffix || 'post-new.php' == $hook_suffix ) {
         wp_enqueue_script( 'custom_js', get_template_directory_uri() . '/inc/meta/custom.js', array( 'jquery' ));
         wp_enqueue_style( 'custom_css', get_template_directory_uri() . '/inc/meta/custom.css')
      }
    }
    add_action( 'admin_enqueue_scripts', 'specific_enqueue' );
    
  2. Use admin_enqueue_scripts hook to enqueue scripts to the admin pages and to make it to specific page follow the below:–

    function specific_enqueue( $hook ) {
        if( 'post.php' != $hook )
            return;
        wp_enqueue_script( 'custom_js', get_template_directory_uri() . '/inc/meta/custom.js', array( 'jquery' ));
        wp_enqueue_style( 'custom_css', get_template_directory_uri() . '/inc/meta/custom.css')
    }
    add_action( 'admin_enqueue_scripts', 'specific_enqueue' );
    

    Hope it helps!!

  3. I have another approach which requires less code. As you are adding the scripts to work with metaboxes, you can equeue the scripts in the add_meta_boxes() action hook. It works perfectly and you don’t need to check the actual page in every request for the admin area.

    function my_meta_boxes() {
    
        add_meta_box("post_meta", "Meta", "post_meta", "post", "normal", "high");
        add_meta_box("post_meta", "Meta", "post_meta", "page", "normal", "high");
        wp_enqueue_script( 'custom_js', get_template_directory_uri() . '/inc/meta/custom.js', array( 'jquery' ));
        wp_enqueue_style( 'custom_css', get_template_directory_uri() . '/inc/meta/custom.css');
    
    }
    add_action( 'add_meta_boxes', 'my_meta_boxes' );
    

Comments are closed.