How to get 4 Posts after the 5 most recent ones

Well, I think the question might be a bit confusing. But well, I want to get the recent 4 posts, ignoring the first five recent posts. So in short the sixth, seventh, eighth and ninth – most recent posts.

Related posts

Leave a Reply

2 comments

  1. Simple.

    WordPress provides a function called get_posts() that lets you get posts in any order. Basically, get_posts() will retrieve the 5 most recent posts by default.

    To get 4 posts, ignoring the 5 most recent, you’d set the numberposts and offset parameters – offset tells the function how many posts to skip.

    $args = array(
        'numberposts' => 4,
        'offset'      => 5,
        'orderby'     => 'post_date',
        'order'       => 'DESC',
        'post_type'   => 'post',
        'post_status' => 'publish'
    );
    
    $posts = get_posts( $args );
    

    Now you have an array of posts the 4 latest posts (ignoring the 5 most recent), ordered by date.

  2. You can use the offset parameter – either on pre_get_posts hook (see this post) for the ‘main Loop’:

    add_action('pre_get_posts','wpse50761_alter_query');
    function wpse50761_alter_query($query){
    
          if( $query->is_main_query() ){
            //Do something to main query
            $query->set('offset',5);
          }
    }
    

    Or for subsequent secondary loops:

     //Using get_posts
     $my_offset_posts = get_posts(array('offset'=>5));
    
     //Using WP_Query object
     $my_offset_query = new WP_Query( array('offset'=> 5) );
    

    (Of course other argument can be included in the argument array)