If you like, that users only can delete his own post, then it is important, that check for the ID of the user and the Author-ID to the post. The follow source example add a Trash button to the admin bar, that the users can easily delete his own post.
The key is the function get_queried_object()
. This object stored all values to the post on the front end and you can check to the user id, there is logged in – get_current_user_id()
. Also important for a strict comparison is, that you set all values to the same type, like integer.
Also is it possible to use the WP core function current_user_can()
with the second param to identifier the rights to each post: current_user_can('edit_post', 123)
this check the capability to the post with the ID 123
. Maybe a little bid easier as the check about the author object and the post object.
Also useful in my example, that you nit must use the global $post
.
add_action( 'admin_bar_menu', 'fb_add_admin_bar_trash_menu', 35 );
function fb_add_admin_bar_trash_menu() {
if ( ! is_super_admin() || ! is_admin_bar_showing() )
return;
$current_object = get_queried_object();
// check, is the objekt with the value readable
if ( ! isset( $current_object->post_author ) )
return;
// check, if the user id the same as the author-id if the current post
if ( (int) $current_object->post_author !== (int) get_current_user_id() )
return;
if ( empty( $current_object ) )
return;
if ( ! empty( $current_object->post_type ) &&
( $post_type_object = get_post_type_object( $current_object->post_type ) ) &&
current_user_can( $post_type_object->cap->edit_post, $current_object->ID )
) {
global $wp_admin_bar;
$wp_admin_bar->add_menu(
array(
'id' => 'delete',
'title' => __( 'Move to Trash' ),
'href' => get_delete_post_link( $current_object->term_id )
)
);
}
}
For the non access to the admin area of non admin is it easier to write a small function include a rewrite, not a hard die. Use the WordPress function wp_redirect()
to rewrite to a specific url or frontend.
add_action( 'admin_init', 'fb_redirect_to_frontend' );
function fb_redirect_to_frontend() {
if ( ! current_user_can( 'remove_users' ) )
wp_redirect( site_url() );
}