6

Because of the lack of documentation about post_limits, its hard to learn more about this function and when to use it. Never used it before or seen it used so maybe its not to be used?

function wpcodex_filter_home_post_limits( $limit, $query ) {

    if ( ! is_admin() && $query->is_main_query() && $query->is_home() ) {
        return 'LIMIT 0, 25';
    }

    return $limit;
}
add_filter( 'post_limits', 'wpcodex_filter_home_post_limits', 10, 2 );

Based on my testing, post_limits does the same thing as using pre_get_posts

If i wanted to return 5 posts conditionally without paginating the remainder, would i use post_limits or pre_get_posts?

5

Note that here you're overriding the paging of the main query, with the posts_limits filter, by using hardcoded values:

'LIMIT 0, 25'

where 0 is the offset and 25 is the number of posts to display.

So in this case I would just use pre_get_posts with

$query->set( 'posts_per_page', 25 );

and we don't have to worry about the paging.

If i wanted to return 5 posts conditionally without paginating the remainder, would i use post_limits or pre_get_posts?

If we later decide that pagination is necessary, then we would need to rework your posts_limits code. The pre_get_posts filter would work as is and we could therefore say that it's at least a more "future proofed" method.

Another thing: If you were using get_posts() or WP_Query() with suppressed filters, then the posts_limits filter wouldn't be available while the pre_get_posts hook would be accessible.

  • Thanks. There'll still be pagination using 'posts_per_page', 25 – Brad Dalton Jun 11 '15 at 12:20
  • yes the pagination of the main query should hold using the posts_per_page in pre_get_posts. So it might be a little more convenient to work with the pre_get_posts hook rather than "hacking" the generated SQL - but I don't see it's wrong in any way ;-) PS: If you're using $query->is_home() then I don't think you'll need the is_admin() check @BradDalton – birgire Jun 11 '15 at 13:12
4

pre_get_posts allows you to alter the query arguments very early on in a request. You can modify anything that would be a valid WP_Query argument, including the LIMIT via the posts_per_page argument. This allows much, much broader range of effects than posts_limits which only allows you to alter one part of the database query SQL.

In your case, use pre_get_posts as the Core code will manage pagination for you ( at least if this is the main query(). If you use post_limits you will need to track and manage the pagination -- the "0,25" part yourself, incrementing values as you page.

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.