Support » Fixing WordPress » Query posts based on if has post thumbnail

  • Resolved gojsse

    (@gojsse)


    Wondering if there is a trick or argument that would allow me to query posts based on if there is an attached thumbnail (aka “featured image”).

    I’m using get_posts() outside of the loop and have queried attachments before but I want to get whole posts ONLY if there is a thumbnail, otherwise the post is skipped. It’s for a homepage slide show and I don’t want to code more than I have to if there is a way to do this already.

Viewing 4 replies - 1 through 4 (of 4 total)
  • esmi

    (@esmi)

    Forum Moderator

    Why not use:

    if( !has_post_thumbnail() ): continue;
    else :
    [ the rest of the Loop ]
    endif;

    I don’t think there’s a specific query for posts with featured images yet.

    I’m only querying for 4 posts so if I skip one after the main query then I will be left with only 3 posts.

    I did find something out though, wp stores the thumbnail in a meta field so you can simply add this to the query: ‘meta_key’ => ‘_thumbnail_id’

    Here’s my example:

    $args = array (
        'numberposts' => 4,
        'post_type'   => 'slide',
        'meta_key'    => '_thumbnail_id',
        'orderby'     => 'date',
        'order'       => 'DESC'
    );

    Tested it and it works! Queries post type of ‘slide’ and skips any that don’t have a thumbnail attached.

    esmi

    (@esmi)

    Forum Moderator

    Oh nice! I forgot about meta fields.

    I had no idea the thumbnail data was stored in a meta field

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Query posts based on if has post thumbnail’ is closed to new replies.