How to load scripts/styles only for a specific Custom Post Type on WP dashboard

How to load scripts/styles only for a specific Custom Post Type on WP dashboard

Sometime, when creating custom post type, we are needed to load some specific scripts/styles on Custom Post ‘Edit’ section on WordPress dashboard. And you want to load these scripts/styles only for that particular custom post type and not for others.

Below is the code snippet which will assist you to achieve this. Put this code inside functions.php file.

/**
 * Snippet Name: Add admin script on custom post types
 */
 function ti_load_admin_cpt_script( $hook ) {

  global $post;

  if ( $hook == 'post-new.php' || $hook == 'post.php' ) {
    if ( 'testimonial' === $post->post_type ) {   
      wp_enqueue_style( 'mystyle_css', get_template_directory_uri() . '/css/admin_test.css',false,'1.1','all');
      wp_enqueue_script( 'myscript_js', get_stylesheet_directory_uri().'/js/my_testimonial_admin_script.js' );
    }
  }
}
add_action( 'admin_enqueue_scripts', 'ti_load_admin_cpt_script', 10, 1 );

Here your custom post type name is testimonial. You might need to use your own path (the path where you have kept your JS/CSS files) for ‘wp_enqueue_style’ and ‘wp_enqueue_script’ functions.