Using WordPress ‘post_limits’ PHP filter

The post_limits WordPress PHP filter allows you to modify the LIMIT clause of a query.

Usage

add_filter('post_limits', 'my_custom_post_limits', 10, 2);

function my_custom_post_limits($limits, $query) {
  // your custom code here
  return $limits;
}

Parameters

  • $limits: (string) The LIMIT clause of the query.
  • $query: (WP_Query) The WP_Query instance (passed by reference).

More information

See WordPress Developer Resources: post_limits

Examples

Modify post limit to show 5 posts

Limit the number of posts displayed to 5.

add_filter('post_limits', 'limit_to_five_posts', 10, 2);

function limit_to_five_posts($limits, $query) {
  // Set the LIMIT clause to 5
  $limits = 'LIMIT 5';
  return $limits;
}

Remove limits for a specific category

Remove the LIMIT clause for posts in the “News” category.

add_filter('post_limits', 'no_limits_for_news_category', 10, 2);

function no_limits_for_news_category($limits, $query) {
  if ($query->is_category('News')) {
    // Remove the LIMIT clause
    $limits = '';
  }
  return $limits;
}

Apply custom limits for custom post type

Apply custom limits only for a custom post type called “Events”.

add_filter('post_limits', 'custom_limits_for_events', 10, 2);

function custom_limits_for_events($limits, $query) {
  if ($query->is_post_type_archive('events')) {
    // Set the LIMIT clause to 10
    $limits = 'LIMIT 10';
  }
  return $limits;
}

Increase limits for search results

Increase the LIMIT clause for search results to display more posts.

add_filter('post_limits', 'increase_limits_for_search', 10, 2);

function increase_limits_for_search($limits, $query) {
  if ($query->is_search()) {
    // Increase the LIMIT clause to 20
    $limits = 'LIMIT 20';
  }
  return $limits;
}

Remove limits for logged-in users

Remove the LIMIT clause for logged-in users.

add_filter('post_limits', 'no_limits_for_logged_in_users', 10, 2);

function no_limits_for_logged_in_users($limits, $query) {
  if (is_user_logged_in()) {
    // Remove the LIMIT clause
    $limits = '';
  }
  return $limits;
}