Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have registered a custom post type 'featured_post'. I am looking for a way to test if the blog home page has any 'featured_post' posts on it and if it has load a javascript file.

The 'featured_post' posts will make a slider at the top of the blog home page. I had this working using sticky posts but I can't work out how to conditionally load the script if there are posts of CPT 'featured_post'.

This is the code that worked for sticky posts:

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

However this does not seem to work and I don't know why:

    if ( is_front_page() && get_post_type('featured_post') ) {
        wp_enqueue_script ('flexslider-js');
    }

Thanks in advance.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

I'm at work at the moment (sorry boss), so I can't test this, but the snippet below should be the proper way of testing if the 'featured_post' post type exists, and then enqueue the script if it has any posts.

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');
    }
}
share|improve this answer
    
That worked perfectly thanks very much! I am pretty new to php but that makes perfect sense now I see it. –  chalky Jul 23 '12 at 7:25

WordPress has a helper function to do exactly this: post_type_exists()

Example:

if ( post_type_exists( 'book' ) ) {
   echo 'the Book post type exists';
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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