Why is wp-login redirecting to the home page when I use this function?

So, first off, if you want to block access to wp-admin, why hook into something that fires on every page load? Hook into admin_init instead.

And, as @MattSmath mentioned, edit isn’t a capability. edit_posts is. Also, admin_init only fires on admin pages, so you can remove is_admin() from your check.

Your revised function:

<?php
add_action('admin_init', 'wpse51831_init');
function wpse51831_init()
{
    if(!current_user_can('edit_posts')) 
    {
        wp_redirect(home_url());
        exit();
    }
}

Bonus: You’re probably not going to want to show your subscriber level users the WordPress admin bar (which links them back to wp-admin). This will hide it:

<?php
add_filter('show_admin_bar', 'wpse51831_hide_admin_bar');
/*
 * hide the admin bar for `subscribers`
 *
 * @uses current_user_can
 * @return boolean
 */
function wpse51831_hide_admin_bar($bool)
{
    if(!current_user_can('edit_posts'))
    {
        $bool = false;
    }
    return $bool;
}

Leave a Comment