wp_set_post_lock()
云策文档标注
概述
wp_set_post_lock() 函数用于标记文章为当前用户正在编辑状态,防止并发编辑冲突。它通过更新文章元数据实现锁定机制。
关键要点
- 函数接受文章 ID 或 WP_Post 对象作为参数,返回锁定时间戳和用户 ID 的数组,失败时返回 false
- 锁定信息存储在 _edit_lock 元字段中,格式为“时间戳:用户ID”
- 如果文章不存在或当前用户未登录,函数将返回 false
代码示例
function wp_set_post_lock( $post ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$user_id = get_current_user_id();
if ( 0 === $user_id ) {
return false;
}
$now = time();
$lock = "$now:$user_id";
update_post_meta( $post->ID, '_edit_lock', $lock );
return array( $now, $user_id );
}注意事项
- 该函数自 WordPress 2.5.0 版本引入,是文章编辑锁定功能的核心组件
- 相关函数包括 wp_refresh_post_lock()、wp_write_post() 和 edit_post(),用于在后台管理界面处理锁定状态
- 开发者应确保在编辑文章前调用此函数,以避免数据覆盖问题
原文内容
Marks the post as currently being edited by the current user.
Parameters
$postint|WP_Postrequired-
ID or object of the post being edited.
Source
function wp_set_post_lock( $post ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$user_id = get_current_user_id();
if ( 0 === $user_id ) {
return false;
}
$now = time();
$lock = "$now:$user_id";
update_post_meta( $post->ID, '_edit_lock', $lock );
return array( $now, $user_id );
}
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |