Do Not Duplicate Posts Array and Offset
If you’ve used WP_query() at any point you’ve probably used ‘Do not duplicate posts,’ or $do_not_duplicate, the standard array for not showing duplicate content in two separate queries. For those of you unsure of what the array looks like, it is the following code, taken from the Codex.
<?php // first query $my_query = new WP_Query('category_name=featured&posts_per_page=2'); while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID // starts an array and puts the post ID in the array ?> <!-- Do stuff... --> <?php endwhile; ?> <!-- Do other stuff... --> <?php // second query if (have_posts()) : while (have_posts()) : the_post(); if (in_array($post->ID, $do_not_duplicate)) continue; // checks if the post is in the array. if yes, skip, if no proceed as usual ?> <!-- Do stuff... --> <?php endwhile; endif; ?>
It’s pretty useful and as long as you know what you’re doing, it will work every time. Likewise, if you have a second custom array, you could use ‘post__not_in’:
<?php $custom_query = new WP_Query(array( 'order' => 'ASC', 'post__not_in' => $do_not_duplicate, 'posts_per_page' => '10', 'offset' => '1' )); ?>
So in the above query, we’re filtering through posts, in ascending order, when the post is not in the ‘do not duplicate’ array. 10 posts per page and then a lesser known query argument, offset of 1, where we’ll start at the first post (which should be passed over if our array is working correctly). But what does ‘offset’ do?
If you know the exact amount of posts that will be in the slider forever and always and it will be unchanging, you don’t necessarily need your ‘do not duplicate’ array. For your second query you can rely solely on ‘offset.’ Sure, it’s not as extensible, but sometimes that’s all you need.
There are a few caveats with ‘offset,’ mainly that it destroys pagination. WordPress already has a solution for you though, seen in the Codex. To summarize, pagination is controlled by ‘offset’ so when you use ‘offset’ in your query, WordPress is like, “WTF, how am I going to page this for you now?”
To backtrack, ‘offset’ is nice if you know that you have a set number of slides, say six, in your slider with each of those slides coming from the latest six posts. If that’s the case, your second query can have an offset of 7, meaning, start on the 7th post. It’s important to note that the count does not start at 0, as is the case in some parts of programming.