Error with “posts_per_page” = -1 when verify my plugin with WordPress Plugin Coding Standards And Php Codesniffer

I am verifying my plugin with wordpress coding standard and php codesniffer but i do not know how to remove this issue:

Disabling pagination is prohibited in VIP context, do not set
      |       | `posts_per_page` to `-1` ever.
      |       | (WordPress.VIP.PostsPerPage.posts_per_page)

I alway use posts_per_page = -1 to get posts to get all posts, i do not know how to get all posts without this.

Related posts

Leave a Reply

2 comments

  1. PHPCS with the WordPress plugin gives this error, for all of the following cases:

    'nopaging'       => true, // Bad.
    'posts_per_page' => 999, // Bad.
    'posts_per_page' => -1, // Bad.
    

    Why? Basically, if you disable paging, then you could run into serious performance issues if the query has the potential to return more results than your server (or client) could handle.

    The rationale seems to be explained in this GitHub issue:

    No LIMIT queries

    Using posts_per_page (or numberposts) with the value set to -1 or an unreasonably high number or setting nopaging to true opens up the potential for scaling issues if the query ends up querying thousands of posts.

    You should always fetch the lowest number possible that still gives you the number of results you find acceptable. Imagine that your site grows over time to include 10,000 posts. If you specify -1 for posts_per_page, you’ll query with no limit and fetch all 10,000 posts every time the query runs, which is going to destroy your site’s performance. If you know you’ll never have more than 15 posts, then set posts_per_page to 15. If you think you might have more than 15 that you’d want to display but doubt it’d hit more than 100 ever, set the limit to 100. If it gets much higher than that, you might need to rethink the page architecture a bit.

    If you want to stop PHPCS from complaining about this, either fix the code to start using paging, or disable these particular checkes by including this code in your phpcs.xml file:

    <exclude name="WordPress.VIP.PostsPerPage.posts_per_page_nopaging" />
    <exclude name="WordPress.VIP.PostsPerPage.posts_per_page_numberposts" />
    

    Update for PHPCS WP version 1.0:

    Version 1.0 no longer includes the WordPress.VIP policies any more, so you might not see this error if you upgrade it. See changelog.