钩子文档

rest_pre_insert_{$this->post_type}

💡 云策文档标注

概述

rest_pre_insert_{$this->post_type} 是一个动态 Hook,用于在通过 REST API 插入文章前进行过滤。它允许开发者修改准备插入数据库的文章数据。

关键要点

  • 这是一个动态 Hook,名称中的 $this->post_type 指代文章类型 slug,例如 rest_pre_insert_post、rest_pre_insert_page。
  • Hook 接收两个参数:$prepared_post(表示准备插入或更新的文章对象)和 $request(WP_REST_Request 对象)。
  • 主要用于在 REST API 创建或更新文章时,对数据进行预处理或验证。

代码示例

add_filter( 'rest_pre_insert_post', 'my_custom_pre_insert_filter', 10, 2 );
function my_custom_pre_insert_filter( $prepared_post, $request ) {
    // 修改 $prepared_post 对象,例如添加自定义字段
    $prepared_post->my_custom_field = 'some_value';
    return $prepared_post;
}

注意事项

  • Hook 名称是动态的,需根据具体文章类型替换,确保正确使用。
  • 参数 $prepared_post 是一个 stdClass 对象,修改时应保持结构兼容。
  • 此 Hook 自 WordPress 4.7.0 版本引入,使用时需注意版本兼容性。

📄 原文内容

Filters a post before it is inserted via the REST API.

Description

The dynamic portion of the hook name, $this->post_type, refers to the post type slug.

Possible hook names include:

  • rest_pre_insert_post
  • rest_pre_insert_page
  • rest_pre_insert_attachment

Parameters

$prepared_poststdClass
An object representing a single post prepared for inserting or updating the database.
$requestWP_REST_Request
Request object.

Source

return apply_filters( "rest_pre_insert_{$this->post_type}", $prepared_post, $request );

Changelog

Version Description
4.7.0 Introduced.