[resolved] Query posts based on if has post thumbnail (5 posts)

  1. gojsse
    Posted 4 years ago #

    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.

  2. esmi
    Forum Moderator
    Posted 4 years ago #

    Why not use:

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

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

  3. gojsse
    Posted 4 years ago #

    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.

  4. esmi
    Forum Moderator
    Posted 4 years ago #

    Oh nice! I forgot about meta fields.

  5. gojsse
    Posted 4 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic