使用"posts_per_page"= -1当验证我的插件与WordPress插件编码标准和Php代


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

我正在验证我的插件与wordpress编码标准和php代码识别器,但我不知道如何消除这个问题:

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

我总是使用posts_per_page = -1来获取所有的帖子,我不知道如何获得所有的帖子没有这个

PHPCS与WordPress插件给出这个错误,对于以下所有情况:

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

为什么?基本上,如果禁用分页,那么如果查询返回的结果可能超出服务器(或客户端)的处理能力,就可能遇到严重的性能问题。

基本原理似乎在这个GitHub问题中得到了解释:

没有LIMIT查询

使用posts_per_page(或numberposts)并将值设置为-1或一个不合理的高数字,或者将nopaging设置为true,如果查询最终查询数千个帖子,则可能会出现扩展问题。

您应该始终获取尽可能低的数字,从而仍然提供您认为可接受的结果数量。想象一下,您的站点随着时间的推移增长到包含10,000个帖子。如果您为posts_per_page指定-1,则查询将没有限制,并且每次查询运行时都会获取所有10,000篇文章,这将破坏站点的性能。如果您知道永远不会有超过15个帖子,那么将posts_per_page设置为15。如果你认为你可能有超过15个你想要显示,但怀疑它会超过100,设置限制为100。如果它比这个高得多,您可能需要重新考虑一下页面架构。

如果您想阻止PHPCS抱怨这个问题,要么修复代码以开始使用分页,要么通过在您的phpcs.xml文件中包含此代码来禁用这些特定的检查:

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

PHPCS WP version 1.0更新:

1.0版本不再包含WordPress.VIP策略,因此如果升级它可能不会看到此错误。看到更新日志。

Just set 'posts_per_page' => PHP_INT_MAX,

这就是我所做的,PHPCS现在很高兴:)