WordPress.org

Ready to get started?Download WordPress

Forums

Conditionally enqueue a script if a custom post type exists (3 posts)

  1. guswhite
    Member
    Posted 1 year ago #

    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.

  2. guswhite
    Member
    Posted 1 year ago #

    this is the code that was working for sticky posts

    if ( is_front_page() &&  is_sticky() ) {
                wp_enqueue_script ('flexslider-js');
            }
  3. guswhite
    Member
    Posted 1 year ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic