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 a function that I thought should find the first article with a featured image in it, and then return that image. Not sure if this is the best way to go about it, as it's giving me a 502 Bad Gateway...

function get_category_post($cat_id){
        $finished = false;
        $postcount = 0;
        $post_args = array(
            'numberposts' => 1,
            'category' => $cat_id,
            'fields' => 'ids'
        );
        $posts = get_posts($post_args);
        while ( $finished != true ) {
            if ( has_post_thumbnail($posts[$postcount]) ) {
                $postthumb = get_the_post_thumbnail($posts[$postcount], $size = 'thumbnail');
                $finished = true;
            }
            $postcount++;
        }
        return $postthumb;
    }
share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

The ID of the featured image is stored under the meta key _thumbnail_id, so we can do a query for a single post that has this key:

$args = array(
    'posts_per_page' => 1,
    'meta_key' => '_thumbnail_id',
    'cat' => $cat_id
);
$latest_thumb = new WP_Query( $args );

if( $latest_thumb->have_posts() )
    return get_the_post_thumbnail( $latest_thumb->post->ID );
share|improve this answer
    
This one worked perfectly, and it's simpler than my previous structure. Thanks for the help! –  Jake Lisby Jan 5 '13 at 19:55
add comment

As discussed over here, you need to use the meta_key parameter in your $post_args array, like this:

$post_args = array(
    'category'    => $cat_id,
    'fields'      => 'ids',
    'numberposts' => 1,
    'meta_key'    => '_thumbnail_id'
);

I'm not sure a while loop is needed for this. I would probably rewrite your function like this (haven't tested yet):

function get_category_post($cat_id){

    $post_args = array(
        'category'    => $cat_id,
        'fields'      => 'ids',
        'numberposts' => 1,
        'meta_key'    => '_thumbnail_id'
    );

    $post_id = get_posts( $post_args );

    return get_the_post_thumbnail( $post_id[ 0 ], 'thumbnail' );
}
share|improve this answer
add comment

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.