Jagan K
Jagan K

Reputation: 1057

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

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?

Upvotes: 5

Views: 8800

Answers (3)

nomeq
nomeq

Reputation: 11

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');

Upvotes: 1

jogesh_pi
jogesh_pi

Reputation: 9782

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');

Upvotes: 10

alexg
alexg

Reputation: 3045

You could include the value of get_post_type() in your condition.

if(is_single() && get_post_type()=='CustomPostTypeName' )
    add_action('wp_enqueue_scripts', 'build_js');

Upvotes: 0

Related Questions