5

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?

3 Answers 3

10

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');
3
  • Can you please explain why? Why should an action be performed un necessarily? Why is_single() fails in the first place?
    – Jagan K
    Nov 22, 2013 at 7:20
  • @JaganK I am not sure but as i know this is because of action_hooks, my guess is all these hooks and filters initiating before rendering entire page.
    – jogesh_pi
    Nov 22, 2013 at 7:41
  • You can also "pre register" de script using wp_register_script and enqueue when you need it.
    – laviku
    Mar 27, 2019 at 13:03
1

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.