_wp_put_post_revision()
云策文档标注
概述
_wp_put_post_revision() 函数用于将文章数据作为修订版本插入到 posts 表中。它处理参数转换、验证,并调用 wp_insert_post() 来创建修订,同时触发相关 Hook。
关键要点
- 参数 $post 可以是整数、WP_Post 对象、数组或 null,默认 null;$autosave 为布尔值,指示是否为自动保存,默认 false。
- 返回值为整数(成功时为新修订 ID)或 WP_Error(错误时)。
- 函数内部会检查文章 ID 的有效性,并防止为修订版本创建修订。
- 使用 _wp_post_revision_data() 准备数据,wp_slash() 处理转义,wp_insert_post() 插入修订。
- 成功创建修订后,会触发 do_action('_wp_put_post_revision', $revision_id, $post['post_parent']) Hook。
代码示例
function _wp_put_post_revision( $post = null, $autosave = false ) {
if ( is_object( $post ) ) {
$post = get_object_vars( $post );
} elseif ( ! is_array( $post ) ) {
$post = get_post( $post, ARRAY_A );
}
if ( ! $post || empty( $post['ID'] ) ) {
return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
}
if ( isset( $post['post_type'] ) && 'revision' === $post['post_type'] ) {
return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
}
$post = _wp_post_revision_data( $post, $autosave );
$post = wp_slash( $post ); // Since data is from DB.
$revision_id = wp_insert_post( $post, true );
if ( is_wp_error( $revision_id ) ) {
return $revision_id;
}
if ( $revision_id ) {
do_action( '_wp_put_post_revision', $revision_id, $post['post_parent'] );
}
return $revision_id;
}注意事项
- 此函数是内部函数,通常由更高级的 API(如 wp_save_post_revision())调用,开发者应优先使用公共函数。
- 参数 $post 必须包含有效的文章 ID,否则会返回 WP_Error。
- 修订版本不能基于另一个修订版本创建,否则会返回错误。
- 函数在 WordPress 2.6.0 中引入,适用于创建文章修订或自动保存。
原文内容
Inserts post data into the posts table as a post revision.
Parameters
$postint|WP_Post|array|nulloptional-
Post ID, post object OR post array.
Default:
null $autosavebooloptional-
Whether the revision is an autosave or not.
Default:
false
Source
function _wp_put_post_revision( $post = null, $autosave = false ) {
if ( is_object( $post ) ) {
$post = get_object_vars( $post );
} elseif ( ! is_array( $post ) ) {
$post = get_post( $post, ARRAY_A );
}
if ( ! $post || empty( $post['ID'] ) ) {
return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
}
if ( isset( $post['post_type'] ) && 'revision' === $post['post_type'] ) {
return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
}
$post = _wp_post_revision_data( $post, $autosave );
$post = wp_slash( $post ); // Since data is from DB.
$revision_id = wp_insert_post( $post, true );
if ( is_wp_error( $revision_id ) ) {
return $revision_id;
}
if ( $revision_id ) {
/**
* Fires once a revision has been saved.
*
* @since 2.6.0
* @since 6.4.0 The post_id parameter was added.
*
* @param int $revision_id Post revision ID.
* @param int $post_id Post ID.
*/
do_action( '_wp_put_post_revision', $revision_id, $post['post_parent'] );
}
return $revision_id;
}
Hooks
- do_action( ‘_wp_put_post_revision’, int $revision_id, int $post_id )
-
Fires once a revision has been saved.
Changelog
| Version | Description |
|---|---|
| 2.6.0 | Introduced. |