3

I'm using the following query for a custom post type:

<?php
             $posts = get_posts(array(
                'numberposts' => -1,
                'offset' => 20,
                'post_type' => 'faqs'

             ));


            if($posts)
            {

                foreach($posts as $post)
                {
                    echo '<li class="faq">
                        <p class="title"><a href="' . get_permalink($post->ID) . '">' . get_the_title($post->ID) . '</a></p></li>';
                        /*<h4 class="title"><a href="' . get_permalink($post->ID) . '">' . get_the_title($post->ID) . '</a></h4><p>' . get_the_excerpt($post->ID) . '</p></li>'; */
                }

            }
             wp_reset_query();
            ?>

Is there a reason as to why the offset parameter doesn't work? Perhaps I need to write an entirely different query altogether?

2 Answers 2

1

Reason of this behavior is pretty simple. First of all you have to know that get_posts uses WP_Query to get posts.

So let's look at WP_Query implementation. On line 1998 of query.php you can find:

if ( $q['posts_per_page'] == -1 ) {
    $q['nopaging'] = true;

Then on line 2544 of query.php you find:

if ( empty($q['nopaging']) && !$this->is_singular ) {
    $page = absint($q['paged']);
    if ( !$page )
        $page = 1;

    if ( empty($q['offset']) ) {
        $pgstrt = ($page - 1) * $q['posts_per_page'] . ', ';
    } else { // we're ignoring $page and using 'offset'
        $q['offset'] = absint($q['offset']);
        $pgstrt = $q['offset'] . ', ';
    }
    $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
}

It's the only part where LIMIT for posts is added. And, as you can see, it is added only if nopaging is not set. So if posts_per_page is set to -1, then paging part of SQL query is not added.

So what can you do to work it around? You can set numberofposts to some big positive number.

0

Set 'numberposts' value to a large positive number. With numberposts set to -1 it will return all the faqs ignoring the offset value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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