WordPress.org

Make WordPress Core

Opened 4 years ago

Closed 4 years ago

Last modified 4 years ago

#36889 closed defect (bug) (invalid)

WP_Query 'post_limits' filter conflicting with 'posts_per_page' parameter

Reported by: romulodl Owned by:
Milestone: Priority: normal
Severity: normal Version: 4.5.2
Component: Query Keywords:
Focuses: Cc:

Description

If I hook in 'post_limits' or 'post_limits_request' to set a different limit and then query using 'posts_per_page'. the max_num_pages variables will follow the 'posts_per_page' param and not the 'post_limits' filter.

<?php
    // supposing I have 10 published posts in the DB    
    add_filter('post_limits', function($limit) {
        return 'LIMIT 0, 1';
    });

    $query = new WP_Query(array('posts_per_page' => 5));

    var_dump($query->max_num_pages); 
    //=> It will be 2, should not be 10 because I am forcing LIMIT 0, 1?

My question is what it should be the correct behaviour? Obey the 'post_limits' filter? Obey the 'posts_per_page' parameter?

Change History (3)

#1 @dd32
4 years ago

  • Milestone Awaiting Review deleted
  • Resolution set to invalid
  • Status changed from new to closed

Hey @romulodl and welcome to trac!

Filters such as post_limits are sufficiently low-level that it's unrealistic to expect the resulting WP_Query to know about what has happened at the SQL level.

As far as WP_Query knows, it's paginated to 5 posts per page, and it's been told there's 10 results. It can't really be expected to parse the SQL and figure out that it's changed, just the same as all the query variables don't update to reflect extra conditionals added through the posts_where_paged filter.

It's entirely possible that the function hooked to the filter could use the instance passed as the 2nd parameter to the filter to manipulate the WP_Query instance to make it aware of the new parameters.

But I'd suggest the for 99% of cases, including the example here, using pre_get_posts to alter the posts_per_page would be the much smarter move, leaving the SQL filters for literal last measure when needing to alter the underlying query.

I'm marking this as invalid, as I don't think we need to write a SQL parser just yet :)

#2 @romulodl
4 years ago

Thanks @dd32 for the quick reply!

This was really related to which should be the expected behaviour of WP_Query in this case.

#3 @dd32
4 years ago

This was really related to which should be the expected behaviour of WP_Query in this case.

In that case, exactly the same behaviour as present, for reasons outlined above.

Note: See TracTickets for help on using tickets.