钩子文档

rest_{$this->post_type}_collection_params

💡 云策文档标注

概述

rest_{$this->post_type}_collection_params 是一个 WordPress REST API 过滤器,用于修改文章控制器的集合参数。它允许开发者自定义特定文章类型的查询参数,但不直接映射到 WP_Query 参数。

关键要点

  • 过滤器名称是动态的,基于 $this->post_type(文章类型 slug),用于注册集合参数。
  • 此过滤器不映射集合参数到内部 WP_Query 参数;需使用 rest_{$this->post_type}_query 过滤器来设置 WP_Query 参数。
  • 参数包括 $query_params(JSON Schema 格式的集合参数数组)和 $post_type(WP_Post_Type 对象)。
  • 在 WP_REST_Posts_Controller::get_collection_params() 方法中使用,用于检索文章集合的查询参数。
  • 自 WordPress 4.7.0 版本引入。

代码示例

add_filter("rest_{$post_type}_collection_params", function($params) {
    if ( isset($params['per_page']) ) {
        $params['per_page']['maximum'] = $n;
    };
    return $params;
});

注意事项

此过滤器仅影响集合参数的注册,不直接修改查询逻辑;确保使用正确的过滤器来调整 WP_Query 行为。


📄 原文内容

Filters collection parameters for the posts controller.

Description

The dynamic part of the filter $this->post_type refers to the post type slug for the controller.

This filter registers the collection parameter, but does not map the collection parameter to an internal WP_Query parameter. Use the `rest_{$this->post_type}_query` filter to set WP_Query parameters.

Parameters

$query_paramsarray
JSON Schema-formatted collection parameters.
$post_typeWP_Post_Type
Post type object.

Source

return apply_filters( "rest_{$this->post_type}_collection_params", $query_params, $post_type );

Changelog

Version Description
4.7.0 Introduced.

User Contributed Notes