0

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;
    }
3

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 );
  • This one worked perfectly, and it's simpler than my previous structure. Thanks for the help! – Jake Lisby Jan 5 '13 at 19:55
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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