Wordpress - Load a script just to custom post type in admin
Try this code for adding scripts to the edit pages of your portfolio custom post type.
add_action( 'admin_print_scripts-post-new.php', 'portfolio_admin_script', 11 );
add_action( 'admin_print_scripts-post.php', 'portfolio_admin_script', 11 );
function portfolio_admin_script() {
global $post_type;
if( 'portfolio' == $post_type )
wp_enqueue_script( 'portfolio-admin-script', get_stylesheet_directory_uri() . '/admin.js' );
}
I'll post a better solution because the accepted answer is old and does not use the right hooks.
First of all: To enqueue scripts and styles in admin area, must be used admin_enqueue_scripts
and nothing else.
Second: Forget any global vars. Use the current screen object to perform different checks.
Here is a ready copy paste code:
<?php
function wpse_cpt_enqueue( $hook_suffix ){
$cpt = 'portfolio';
if( in_array($hook_suffix, array('post.php', 'post-new.php') ) ){
$screen = get_current_screen();
if( is_object( $screen ) && $cpt == $screen->post_type ){
// Register, enqueue scripts and styles here
}
}
}
add_action( 'admin_enqueue_scripts', 'wpse_cpt_enqueue');
Note: Replace 'portfolio'
with the needed post type slug.