• I have a “magazine” type page that uses multiple query loops built with WP_Query($args).

    I’d like to be able to ensure only Posts that haven’t been queried yet get caught in the queries below it.

    For example, Suppose the post “Hello World” was in the Category News, and Culture.

    One query loop (WP_Query) queriest for posts in News, and Hello World is displayed.

    The next query loop on the page queries for Culture. Since Hello World is in Culture, too, it will be displayed, again.

    Is there a way to ensure that this doesn’t happen? Maybe each query loop updates some an array of the posts it displays, then each query loop will exclude those posts?

Viewing 2 replies - 1 through 2 (of 2 total)
  • You’d need to track each query and record the ID’s of the posts that they return are, and use that as an ‘exclude’ attribute for each next query after that. There’s a bit of work to it and can be done in different ways depending on how all of your queries are set up, but it’s definately possible.

    There will probably be multiple solutions for this, but the way I would probably tackle it would be to create an empty array variable at the top of the page:

    $displayed_posts = array();

    Then as you loop through each post in your queries, add their IDs to that array. So inside the loop, you would have something like this:

    $displayed_posts[] = $post->ID;

    or

    $displayed_posts[] = get_the_ID();

    (depending on how you’re using the loop)

    This means you will build up an array of IDs of posts already shown and it will be added to in each new query.

    Then in every query on the page after the first one, you can you the post__not_in parameter to exclude any posts that you have already shown:

    'post__not_in' => $displayed_posts,

    The post__not_in parameter takes an array of post IDs and excludes them from the query so they won’t show up at all.

    There will probably be some other methods, but that feels like the cleanest one to me. If you are needing to use that array over multiple PHP files, then you can instantiate it as a global at the top of each file you need it in:

    global $displayed_posts;

    That way it will be available in all files and templates and will remain consistent.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Page w/multiple post queriest: how to only show unique?’ is closed to new replies.