I have a custom post type, that can be editable by more than one user.
Each post of that type has a field with the user ids who can edit it (kinda like co-authors).
But since many users have permissions to the post, I am not sure how to prevent deletion by other users (not in the co-authors’ list).
Right now the problem is only present in the REST API which is used to delete from the frontend.
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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
pre_delete_post hook filters whether a post deletion should take place. So callback function must return a boolean value: true – whether to go forward with deletion, false – if not.
pre_trash_post hook filters whether a post trashing should take place. So callback function must return a boolean value: true – whether to go forward with trashing, false – if not.
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;
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0