WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] WP_Query returning more items than it should (more than found_posts) (3 posts)

  1. shen045
    Member
    Posted 1 year ago #

    I am trying to write a custom query to populate a slider for my home page. I want to return all sticky posts that have a featured image/thumbnail associated.

    I am using WP_Query and have found examples showing how to filter to stickies, and how to filter to only posts that have thumbnails. The sticky filter works, but the thumbnail post doesn't work properly.

    Currently, I have 5 sticky posts, but only 2 have thumbnails, so I am expecting 2 posts to be displayed. $found_posts correctly says that there are 2 posts that match, however, post_count is 5 and all 5 are showing up in the loop.

    The code I am using is here in this pastebin: http://pastebin.com/aJz2cyhA.
    I have tried a number of different variations, including specifying greater than 0 or not empty for the _thumbnail_id. I've also tried using meta_key rather than a meta_query and turning on and off paging, but nothing seems to make any difference.

    (I do know I can work around this by checking has_thumbnail before I output the slider content for that post, but I really want to know what I am doing wrong with this query, in case I make the same mistake in other places.)

    Any suggestions appreciated!

  2. shen045
    Member
    Posted 1 year ago #

    I found the solution for this, and I'll post it here in case anyone else runs into this. Even though the entire purpose of my query is to get a list of all the stickies, I have to add this line to my query options:

    'ignore_sticky_posts' => 1

    Without this line of code, WordPress will run the query and then add all other sticky posts to the results, regardless of whether they meet my other query parameters. With this line of code, stickies are just treated as ordinary posts and can be queried normally.

  3. esmi
    Forum Moderator
    Posted 1 year ago #

    This is clearly documented in the relevant Codex page.

Topic Closed

This topic has been closed to new replies.

About this Topic