Filter DELETE REST API calls

时间:2020-10-03 作者:CaptainNemo

我有一个自定义的帖子类型,可以由多个用户编辑。这种类型的每篇文章都有一个带有用户ID的字段,用户ID可以对其进行编辑(有点像合著者)。但由于许多用户都有该帖子的权限,我不知道如何防止其他用户删除该帖子(不在合著者列表中)。

目前,这个问题只存在于用于从前端删除的REST API中。

Is there a pre delete hook in which I can check for permissions and block the deletion if the user is not allowed to delete that specific post?

1 个回复
最合适的回答,由SO网友:geouser 整理而成

pre_delete_post 钩子过滤器是否为立柱deletion 应该发生。因此回调函数必须返回布尔值:true - 是否继续删除,false - 如果没有。

pre_trash_post 钩子过滤器是否为立柱trashing 应该发生。因此回调函数必须返回布尔值:true - 是否继续进行垃圾清理,false - 如果没有。

add_filter( \'pre_delete_post\', \'filter_function_name\', 10, 2 );
add_filter( \'pre_trash_post\', \'filter_function_name\', 10, 2 );

function filter_function_name( $delete, $post ) {

    // You have a field with user IDs for the post, get them as array of IDs
    $authors = array(1, 2, 3);
    
    // Get current user ID, who attempts to delete the post
    $current_user_ID = get_current_user_id();
    
    // make a check if the current user ID is among the co-authors IDs
    if ( !in_array( $current_user_ID, $authors ) ) {
        // If so, return false to prevent post deletion
        return false;
    }
    
    // else do nothing, and return default value
    return $delete;
}