Can I use numberposts=-1 and offset together when using get_posts()?

I’m currently using get_posts() for a little part of a theme I’m working on. However, I’ve run into one little hiccup.

If I want to show all posts for a category, I set the ‘numberposts’ argument to ‘-1’. However the issue is that when I do this, the offset no longer works.

Read More

I do see that I’m telling the function to return all posts, but then I’m expecting it to not actually return all posts. So, I do see the dilemma in the logic.

So using get_posts, is there a way to show all posts except for posts offset at the beginning? I realize there are a few hacky ways you could this, but I’m just wondering if I’m doing something incorrectly here that is obvious? I’d like to work within the constraints of the get_posts function if possible.

I did start to rig up something sort of hacky. This works, but wondering if there was another way to go about this.

// Get posts
$posts = get_posts( $args );

// Adjust offset if neccesary
if( $args['numberposts'] == -1 && $args['offset'] > 0 ) {
    $i = 0;
    while ( $i < $args['offset'] ) {
        unset( $posts[$i] );
        $i++;
    }
}

// ... now do my foreach() and setup_postdata

Visual representation

Related posts

Leave a Reply

1 comment

  1. I believe the issue is that the underlying MySQL query requires a LIMIT clause to go with the OFFSET clause. (I tried to verify this about MySQL and found this https://stackoverflow.com/questions/255517/mysql-offset-infinite-rows ). Since MySQL can’t accept those parameters (offset without a limit), WordPress seems to drop the offset argument.

    It’s still a little hacky, but I think your only other option would be to set an arbitrarily high number for the ‘numberposts’ argument. I think it’s safe to say you wouldn’t want more than, say, 500 posts returned. So you could use:

    $posts = get_posts(array(
        'offset'    =>  2,
        'numberposts'   =>  500,
    ));
    

    numberposts is just a limit, so it shouldn’t cause any problems. You could go higher if necessary (MySQL seems to suggest 18446744073709551615 as a max).

    From what I can tell looking at the core code, that seems like the best you can do. Hope it helps!