wp_insert_post_data
云策文档标注
概述
wp_insert_post_data 是一个 WordPress 过滤器,用于在文章数据插入数据库前修改已处理的数据。它接收多个参数,包括已处理、未处理的数据和更新状态,允许开发者自定义文章内容。
关键要点
- 过滤器在文章数据插入数据库前触发,可修改 $data 数组中的字段。
- 参数包括 $data(已处理数据)、$postarr(已处理但未修改数据)、$unsanitized_postarr(未处理原始数据)和 $update(更新标志)。
- 使用 add_filter() 时,需设置 $accepted_args 为 2 以访问 $postarr 参数。
- 可通过 $postarr['ID'] 获取文章 ID,但需注意在特定情况下可能不可用。
- 过滤器也适用于文章更新和删除操作,不限于插入。
代码示例
// 移除文章标题中的 HTML 实体
function filter_post_name( $data, $postarr, $unsanitized_postarr) {
$data['post_title'] = html_entity_decode($data['post_title']);
return $data;
}
add_filter( 'wp_insert_post_data', 'filter_post_name', 10, 3);注意事项
- 确保正确处理参数,避免数据冲突或安全风险。
- 注意 $data 和 $postarr 的默认字段差异,如 $data 包含更多标准字段。
- 在修改数据时,考虑更新和删除场景的影响。
原文内容
Filters slashed post data just before it is inserted into the database.
Parameters
$dataarray-
An array of slashed, sanitized, and processed post data.
$postarrarray-
An array of sanitized (and slashed) but otherwise unmodified post data.
$unsanitized_postarrarray-
An array of slashed yet *unsanitized* and unprocessed post data as originally passed to wp_insert_post() .
$updatebool-
Whether this is an existing post being updated.
Source
$data = apply_filters( 'wp_insert_post_data', $data, $postarr, $unsanitized_postarr, $update );
Skip to note 3 content
Dnyanesh Mahajan
//Removing & or any html special enitiy from name function filter_post_name( $data, $postarr, $unsanitized_postarr){ $data['post_title'] = html_entity_decode($data['post_title']); return $data; } add_filter( 'wp_insert_post_data', 'filter_post_name',10,3);Skip to note 4 content
Feast Design Co.
Contrary to the name, this hook also runs on post update and post delete.