函数文档

wp_check_post_lock()

💡 云策文档标注

概述

wp_check_post_lock() 函数用于检测指定文章是否正被其他用户编辑,基于文章元数据中的锁信息进行判断。它返回锁定用户的 ID 或 false,适用于防止编辑冲突的场景。

关键要点

  • 参数 $post 为必需,可以是文章 ID 或 WP_Post 对象,用于指定要检查的文章。
  • 返回值:若文章被其他用户锁定,则返回该用户 ID;否则返回 false,包括文章不存在、未锁定、锁定用户不存在或锁定者为当前用户等情况。
  • 函数内部通过 get_post_meta() 获取 _edit_lock 元数据,解析时间戳和用户 ID,并应用 wp_check_post_lock_window 过滤器来定义锁定时长窗口。
  • 相关钩子:apply_filters('wp_check_post_lock_window', int $interval) 可用于自定义锁定时长。

代码示例

function wp_check_post_lock( $post ) {
    $post = get_post( $post );

    if ( ! $post ) {
        return false;
    }

    $lock = get_post_meta( $post->ID, '_edit_lock', true );

    if ( ! $lock ) {
        return false;
    }

    $lock = explode( ':', $lock );
    $time = $lock[0];
    $user = isset( $lock[1] ) ? (int) $lock[1] : (int) get_post_meta( $post->ID, '_edit_last', true );

    if ( ! get_userdata( $user ) ) {
        return false;
    }

    /** This filter is documented in wp-admin/includes/ajax-actions.php */
    $time_window = apply_filters( 'wp_check_post_lock_window', 150 );

    if ( $time && $time > time() - $time_window && get_current_user_id() !== $user ) {
        return $user;
    }

    return false;
}

注意事项

  • 函数自 WordPress 2.5.0 版本引入,广泛用于后台文章编辑、REST API 和自定义器等模块。
  • 使用时需确保文章数据有效,并注意返回值 false 的多种情况,以避免误判。

📄 原文内容

Determines whether the post is currently being edited by another user.

Parameters

$postint|WP_Postrequired
ID or object of the post to check for editing.

Return

int|false ID of the user with lock. False if the post does not exist, post is not locked, the user with lock does not exist, or the post is locked by current user.

Source

function wp_check_post_lock( $post ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return false;
	}

	$lock = get_post_meta( $post->ID, '_edit_lock', true );

	if ( ! $lock ) {
		return false;
	}

	$lock = explode( ':', $lock );
	$time = $lock[0];
	$user = isset( $lock[1] ) ? (int) $lock[1] : (int) get_post_meta( $post->ID, '_edit_last', true );

	if ( ! get_userdata( $user ) ) {
		return false;
	}

	/** This filter is documented in wp-admin/includes/ajax-actions.php */
	$time_window = apply_filters( 'wp_check_post_lock_window', 150 );

	if ( $time && $time > time() - $time_window && get_current_user_id() !== $user ) {
		return $user;
	}

	return false;
}

Hooks

apply_filters( ‘wp_check_post_lock_window’, int $interval )

Filters the post lock window duration.

Changelog

Version Description
2.5.0 Introduced.