Preventing the trash post action is a crude way of approaching it. You have to kill the application and display an ugly error message, and the UI for deleting the post will still be there.
Instead I suggest using the map_meta_cap
filter. This will allow you to change a user’s capabilities for a single post.
Normally when WordPress checks if a user can delete a post it checks “can the user delete_post
for this post?”. The way it figures this out is with the map_meta_cap
function.
This function decides which capabilities delete_post
maps to. For example, if the user created the post then the function maps delete_post
to delete_posts
. So if the user has the delete_posts
capability then they can delete the post. If the user did not create the post, then the function maps delete_post
to delete_others_posts
.
The map_meta_cap
filter allows us change this mapping. So we’ll use it to map delete_post
to do_not_allow
for this specific post. Then no users will be able to delete that post.
This is the function for doing this:
function wpse_312694_restrict_page_deletion( $caps, $cap, $user_id, $args ) {
$post_id = $args[0];
if ( $cap === 'delete_post' && $post_id === 117 ) {
$caps[] = 'do_not_allow';
}
return $caps;
}
add_filter( 'map_meta_cap', 'wpse_312694_restrict_page_deletion', 10, 4 );