We have developed an order system with WordPress, when a user submits an order in the foreground, the order information is saved in a custom post type, customer service can view and process the order in the background. In order to prevent the customer service accidentally delete this order information, we need to disable the delete function of this order, customer service can only view, edit, can not delete the order. We are through the following code can realize this requirement.
Remove user permission to delete a post type
add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args )
{
// 如果不是 delete_post 权限,什么都不做
if( 'delete_post' !== $cap || empty( $args[0] ) ){
return $caps;
}
// 如果是指定的文章类型,修改权限为 do_not_allow
if( in_array( get_post_type( $args[0] ), [ 'messages', 'transaction' ], true ) ){
$caps[] = 'do_not_allow';
}
return $caps;
}, 10, 4 );
After the removal, the only function left is "Edit" in the action bar of the article category label, as shown in the figure below:
Remove the "Move to Recycle Bin" link from batch operations
Although we have removed the user's permission to delete post types, the "Move to Trash" feature of the Post Type List Bulk Edit function is still there (as shown below), so if we select a few posts, choose the "Move to Trash" action, and click Apply, WordPress will report an error telling us that we don't have permission to delete the posts. WordPress will report an error telling us that we don't have permission to delete posts.
We can remove this functionality with the following code:
add_filter('bulk_actions-edit-message', function ($actions) { unset($actions[ 'trash' ]). return $actions. }).
In addition to prohibiting users from deleting posts, we can also prohibit users from performing other operations, according to the need to restrict the corresponding permissions can be, WordPress permissions list please refer to the official document:WordPress Roles and Permissions. If you need other role users can delete the order, you can add the permission judgment in the above code, if you need to edit your own friends, we will not list it here.
2 thoughts on “在 WordPress 中禁止用户删除某些文章类型中的文章”
How do I have to specify that deletions are not allowed except for administrators and editors?
When executing the above code, judge the permissions, if it is an administrator or editor, do not execute the code on the line.