1

I am using this code and I am not sure why the script is not loaded. I believe the syntax is correct since I am trying to load the script only on the "events" custom post type single posts.

add_action( 'login_enqueue_scripts', 'wpse_login_enqueue_scripts', 10 );
function wpse_login_enqueue_scripts() {
    if( is_single() && get_post_type()=='events' ){
    wp_enqueue_script( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js', array('jquery'), '3.3.5', true );
}
}

3 Answers 3

2

To enqueue scripts on the front-end, the hook should be wp_enqueue_scripts, not login_enqueue_scripts.

Also, a better way to see if you’re on a single custom post type is to use is_singular() and pass the post type you want to check:

if ( is_singular( 'events' ) ) {
}

get_post_type() relies on the global $post object, and not the main query. They're often the same but under some circumstances the $post object might not be the same post as the current single post.

3
  • ah, nice catch -- edit -- though this is a more elegant solution, to be 100% accurate it should be noted that is_single() does return true for all post types (any post type, except attachments and pages, see: is_single() )
    – Iceable
    Commented Aug 1, 2018 at 17:12
  • great, and I thought I was doing everything right lol
    – JoaMika
    Commented Aug 1, 2018 at 17:16
  • @Iceable You're right. Amending my answer. Commented Aug 2, 2018 at 11:31
0

this hook is only fired on the login page :
https://developer.wordpress.org/reference/hooks/login_enqueue_scripts/

to use on a custom post page, use the action wp_enqueue_scripts.

0

You are hooking this function to 'login_enqueue_scripts' (which only runs on the login page) ; you sould hook it to 'wp_enqueue_scripts' instead.

Also ( is_single() && get_post_type()=='events' ) would work, but as Jacob Peattie pointed out in another answer, is_singular( 'events' ) is the best way to check for a custom post type single post.

Lastly you should rename the function from wpse_login_enqueue_scripts() to something like wpse_events_enqueue_scripts() to make it more descriptive and less confusing:

add_action( 'wp_enqueue_scripts', 'wpse_events_enqueue_scripts', 10 );
function wpse_events_enqueue_scripts() {
    if ( is_single() && 'events' == get_post_type() ) {
        wp_enqueue_script( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js', array('jquery'), '3.3.5', true );
    }
}

Your Answer

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

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