0

I'm trying to exclude the latest two blog posts from a page. I know it's possible to do this with offset however doing that causes a bug in which some of the blog posts are repeated on the second page so not ideal. Currently I'm doing it manually using the post id so like this:

$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : '1';
$args = array(
    'posts_per_page' => 5,
    'post__not_in'   => array(827, 809),
    'post_status'    =>"publish",
    'post_type'      =>"post",
    'orderby'        =>"post_date",
    'cat'            =>'-1, -8, -9, -7, -6, -5, -4',
    'paged'          => $paged
);

$postslist = get_posts( $args );
echo '<div class="latest_new_posts main-news">';

Can anybody think of a better way of doing this where I don't have to adjust the post id constantly?

1

You could do this using two queries, which is a little bulky but not completely unreasonable.

Get two most recent posts

<?php

$most_recent_args = array(
    'posts_per_page' => 2,
    'paged'          => 1,
    'fields'         => 'ids',
    'orderby'        => 'post_modified',
    'order'          => 'DESC',
);

$most_recent = new WP_Query( $most_recent_args );

Then, you can use the results there to...

Modify your query with the two most recent posts

$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : '1';

$args = array(
    'posts_per_page' => 5,
    'post__not_in'   => $most_recent->posts,
    'post_status'    =>"publish",
    'post_type'      =>"post",
    'orderby'        =>"post_date",
    'cat'            =>'-1, -8, -9, -7, -6, -5, -4',
    'paged'          => $paged
);

$postslist = get_posts( $args );
echo '<div class="latest_new_posts main-news">';
| improve this answer | |
0

You can use offset to exclude the latest posts. Your arguments can be like:

$args = array( 
    'posts_per_page' => 5, 
    'offset' => 2, 
    'post__not_in' => array(827, 809),
    'post_status'=>"publish",
    'post_type'=>"post",
    'orderby'=>"post_date",
    'cat'=>'-1, -8, -9, -7, -6, -5, -4',
    'paged'=> $paged
);

However as you mentioned, it will break the pagination. There is a workaround, as stated in the codex, and it offers a solution for this.

Using pre_get_posts

You can exclude 2 latest posts from your main query, by using pre_get_posts filter:

function exclude_latest_post( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'offset', '1' );
    }
}

add_action( 'pre_get_posts', 'exclude_latest_post', 1 );

You can check the codex page for the alternative, which I skipped since it's long, and well explained on the codex itself.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.