i found many questions like this but nothing matching to my requirement.Here i need to lock a specific page named settings,not to be deleted by other admins.But it should able to edit. Is there any way to lock a specific page.
2 Answers
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 );
-
Are you sure that the code is running well. After using this set of code the site crashed.– AdarshAug 30, 2018 at 3:47
-
-
its working now .....but its not editable .....i need it to be editable.– AdarshAug 30, 2018 at 4:47
-
Sorry, I left out a bit:
$cap === 'delete_post'
, see updated answer. Aug 30, 2018 at 6:14
found the solution
function restrict_page_deletion($post_ID)
{
$restricted_pageId = 177;
if(($post_ID == $restricted_pageId))
{
echo "You are not authorized to delete this page.";
exit;
}
}
add_action('wp_trash_post', 'restrict_page_deletion', 10, 1);