Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

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

share|improve this question
add comment

1 Answer

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 http://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!

share|improve this answer
    
Awesome, very helpful to get a confirmation ... Glad to know I'm not taking the dummy pills today at least. And the super high number of posts is clever, thanks! –  Jason Oct 5 '11 at 4:11
    
You're welcome! Glad it helped. –  Chris - SevenSpark Oct 5 '11 at 20:51
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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