I have done a bit of research and the answers have all come back “use a plugin”. I don’t want to do this for several reasons not least because most plugins have bloat and I’m perfectly capable of doing this in a lightweight fashion and the answer will stand for others.
- the client can login from anywhere as a custom role
client
- when they login they are taken to a page
/clientusername
– created by admin
- the page only contains material placed there by admin (i.e. there is no functionality for the client to edit the page)
- if anyone else other than that client lands on that page (by typing in the url) they are redirected to the home page
function my_login_redirect( $url, $request, $user ){
if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
if( $user->has_cap( 'client' ) ) {
$client = $user->user_login;
$url = home_url( $client, 'relative');
}
}
return $url;
}
add_filter('login_redirect', 'my_login_redirect', 10, 3 );
I realize there’s a lot more to be done but I’ll leave this here for discussion.
For the client role, use this;
// Add a client user role
$result = add_role( 'client', __(
'Client' ),
array(
'read' => true, // true allows this capability
'edit_posts' => false, // Allows user to edit their own posts
'edit_pages' => false, // Allows user to edit pages
'edit_others_posts' => false, // Allows user to edit others posts not just their own
'create_posts' => false, // Allows user to create new posts
'manage_categories' => false, // Allows user to manage post categories
'publish_posts' => false, // Allows the user to publish, otherwise posts stays in draft mode
'edit_themes' => false, // false denies this capability. User can’t edit your theme
'install_plugins' => false, // User cant add new plugins
'update_plugin' => false, // User can’t update any plugins
'update_core' => false // user cant perform core updates
)
);
and then use the code above to redirect the login if, and only if, it’s a client role.
One the page template Client Page put this before get_header()
:
$current_user = wp_get_current_user();
$client = $current_user->user_login;
$slug = get_post_field( 'post_name', get_post() );
$client = strtolower($client);
if ($client != $slug) {
header("Location: /index.php");
}
and, obviously, we need to let admins see the page;
if (!current_user_can('administrator')) {
$current_user = wp_get_current_user();
$client = $current_user->user_login;
$slug = get_post_field( 'post_name', get_post() );
$client = strtolower($client);
if ($client != $slug) {
header("Location: /index.php");
}
}