Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Talk:Plugin API/Filter Reference/post limits

Limit Sometimes Applies to All Queries?

On some Server environments the limit applies on any query executed on a page, on some others, not. We need to find out why and when this happens.


Actually, this filter will always apply to all queries on the page. Could you show some example code? I think the example on the page is actually wrong. This is correct:

// Original code on commented lines.

// add_filter( 'post_limits', 'my_post_limits' );
add_filter( 'post_limits', 'my_post_limits', 10, 2 );

// function my_post_limits( $limit ) {
function my_post_limits( $limit, $query ) {

//  if ( is_search() ) {
    if ( $query->is_search() ) {
        return 'LIMIT 0, 25';
    }
    return $limit;
}

Note how we are checking whether the current query is a search, instead of whether the main query is one. Many of the conditionals like is_search() should be called on the current query (from the second argument, as above) rather than on the main query. Calling the conditional on the main query would likely result in the limit being applied to every query on the page.

Jdgrimes 15:50, 1 February 2014 (UTC)


You are right. It would also make sense to include is_admin() and $query->is_main_query() checks (and ideally explain them), like we do in pre_get_posts examples. I'd suggest this as an example:

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

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

SergeyBiryukov 09:22, 7 March 2014 (UTC)