Useful Functions for Sites with Subscribers

If you have you have a lot of user accounts for subscribers (or customers if using WooCommerce or Easy Digital Downloads), you might find these functions useful for blocking access to the dashboard and simplifying logins.

Allow Users to Use Their E-mail Address to Login

Your visitors probably already have a lot of usernames to remember. Why make it harder on them? Allow them to user their e-mail address as a username.

<?php
/**
* Allows visitors to log in using e-mail address
*
* @param string username passed by reference
*/
function prefix_authenticate_by_email( &$username ) {
$user = get_user_by( 'email', $username );
if ( false !== $user ) {
$username = $user->user_login;
}
}
add_action( 'wp_authenticate', 'prefix_authenticate_by_email' );

Disable Admin Bar for Specific Users

Most websites look a lot nicer without that black bar across the top. Hide it for users that can’t edit posts.

<?php
/**
* Disables the #wpadmin bar for users without "edit_posts" permissions.
*/
function prefix_hide_admin_bar() {
if ( ! current_user_can( 'edit_posts' ) ) {
add_filter( 'show_admin_bar', '__return_false' );
}
}
add_action( 'after_setup_theme', 'prefix_hide_admin_bar' );
view raw hide-admin-bar.php hosted with ❤ by GitHub

Redirect Users Who Attempt to Access Dashboard

If your users don’t need to access the dashboard, make sure they can’t access it. This code redirects any visitor that doesn’t have permissions to edit posts back to the home page if they attempt to access anything wp-admin.

<?php
/**
* Redirects subscribers back to the home page if they attempt to access the dashboard.
*/
function prefix_redirect_admin() {
if ( ! current_user_can( 'edit_posts' ) && ! defined( 'DOING_AJAX' ) ) {
wp_safe_redirect( home_url() );
exit;
}
}
add_action( 'admin_init', 'prefix_redirect_admin' );
view raw redirect-admin.php hosted with ❤ by GitHub

About Devin

I'm a WordPress developer based in Austin, Texas. I run a little theme shop called DevPress and work for a startup called Cratejoy. Find me on twitter @devinsays.

2 Responses

Leave a Reply