• Hi,

    I am trying to enqueue a .js script on my blog home page only if a custom post type exists. I have registered a custom post type ‘featured_post’ which will be inserted into a slider. I can conditionally add the slider and html for ‘featured_post’ to the home page inside the loop using post_type_exists( 'featured-post' ) but I cannot get the .js file to load conditionally if we are on home and there are any ‘featured-post’ posts.

    I had this working and loading the script conditionally using sticky posts but I cannot get it to work with a custom post type. It will load the script if I use post_type_exists( 'featured-post' ) but in that case it will still load it if there are no ‘featured post’ posts as the post type is registered regardless of whether it contains posts or not.

    Any help would be much appreciated.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter guswhite

    (@guswhite)

    this is the code that was working for sticky posts

    if ( is_front_page() &&  is_sticky() ) {
                wp_enqueue_script ('flexslider-js');
            }
    Thread Starter guswhite

    (@guswhite)

    in case anyone is looking, this works:

    if ( is_front_page() && post_type_exists('featured_post') ) { // We are at the front page, and the post type 'featured_post' is registered.
        $hasposts = get_posts( 'post_type=featured_post' ); // lets check if there is any posts in the 'featured_post' post type.
        if( $hasposts ) { // If we found some posts, lets enqueue the script
            wp_enqueue_script ('flexslider-js');
        }
    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Conditionally enqueue a script if a custom post type exists’ is closed to new replies.