钩子文档

found_posts

💡 云策文档标注

概述

found_posts 是一个 WordPress 过滤器钩子,用于在 WP_Query 执行查询时调整其报告的找到的帖子数量。它常用于自定义分页开发,特别是处理查询偏移量时。

关键要点

  • found_posts 过滤器允许开发者修改 WP_Query 返回的找到的帖子数。
  • 在自定义分页中特别有用,例如当查询包含偏移量时,WordPress 不会自动从 found_posts 中扣除偏移量。
  • 使用此钩子时,需确保未在查询参数中设置 no_found_rows,否则会返回 0 值。
  • 参数包括 $found_posts(整数,找到的帖子数)和 $query(WP_Query 实例,通过引用传递)。

代码示例

$this->found_posts = (int) apply_filters_ref_array( 'found_posts', array( $this->found_posts, &$this ) );

注意事项

  • 确保查询参数中未设置 no_found_rows,以避免返回 0。
  • 此钩子从 WordPress 2.1.0 版本开始引入。

📄 原文内容

Filters the number of found posts for the query.

Parameters

$found_postsint
The number of posts found.
$queryWP_Query
The WP_Query instance (passed by reference).

More Information

This filter hook allows developers to adjust the number of posts that WordPress’s WP_Query class reports finding when it runs a query.

This hook is especially useful when developing custom pagination. For instance, if you are declaring a custom offset value in your queries, WordPress will NOT deduct the offset from the the $wp_query->found_posts parameter (for example, if you have 45 usable posts after an offset of 10, WordPress will ignore the offset and still give found_posts a value of 55).

Make sure you haven’t passed no_found_rows in query arguments, Otherwise you will receive a 0 value in return.

Source

$this->found_posts = (int) apply_filters_ref_array( 'found_posts', array( $this->found_posts, &$this ) );

Changelog

Version Description
2.1.0 Introduced.