How to load certain scripts only on single pages of custom post type in wordpress?

This following fails to load the scripts in the single pages,

if(is_single( ) ) add_action('wp_enqueue_scripts', 'build_js');

Suppose, If i use

Read More
add_action('wp_enqueue_scripts', 'build_js');

the action is performed and scripts are loaded.

I need to perform the action only on single pages of a custom post type. How to do this?

Related posts

Leave a Reply

3 comments

  1. the problem is you have to check for the single page into the function:

    function build_js(){
        if( is_single() && get_post_type()=='CustomPostTypeName' ){
            wp_enqueue_script(....);
        }
    }
    add_action('wp_enqueue_scripts', 'build_js');
    

    instead of

    if(is_single( ) ) add_action('wp_enqueue_scripts', 'build_js');
    
  2. You can simplify the logic further with the WordPress function is_singular() instead.

    function build_js(){
      if( is_singular('CustomPostTypeName') ) {
        wp_enqueue_script(....);
      }
    }
    add_action('wp_enqueue_scripts', 'build_js');