How do I unlock a post programmatically?

At a first glance it makes sense, but…

When exactly would that function be used? When user opens post editor, you can easily hook to that action and set the lock.

But when would you remove it? After saving? No – user is still editing, so the lock should be on.

It should be removed after user has closed the tab or closed the editor – but you can’t hook to these actions from PHP, because there PHP doesn’t get notified about them just before they happen…

So most probably there is no function for removing lock, because there is no use for it in normal usage…

Of course you can still easily remove such lock…

Let’s look what exactly is that lock and how WP sets it:

function wp_set_post_lock( $post_id ) {
    if ( ! $post = get_post( $post_id ) ) {
        return false;
    }
 
    if ( 0 == ( $user_id = get_current_user_id() ) ) {
        return false;
    }
 
    $now = time();
    $lock = "$now:$user_id";
 
    update_post_meta( $post->ID, '_edit_lock', $lock );
 
    return array( $now, $user_id );
}

OK, so it’s stored as custom filed called ‘_edit_lock’, so… Just remove this meta and the lock will be removed.

delete_post_meta( $post_id, '_edit_lock')

Leave a Comment