Thursday, August 28, 2014

Wordpress: Login / Logout / Register

Add these to your theme's functions.php file to...

...hide the admin-bar for non-administrators:

 add_action('set_current_user', 'cc_hide_admin_bar');  
 function cc_hide_admin_bar() {  
      if (!current_user_can('edit_posts')) {  
           show_admin_bar(false);  
      }  
 }  

...redirect non-administrator users after login:

 function soi_login_redirect($redirect_to, $request, $user) {  
      return (is_array($user->roles) && in_array('administrator', $user->roles)) ? admin_url() : site_url();  
 }   
 add_filter('login_redirect', 'soi_login_redirect', 10, 3);  
(Change site_url() if you want to redirect them somewhere else than the home page)

...redirect users after logout:

 add_action('wp_logout','auto_redirect_after_logout');  
 function auto_redirect_after_logout() {  
      wp_redirect( home_url() );  
      exit();  
 }  
(Change home_url() if you want to redirect them somewhere else than the home page)



To add login/logout links to your theme use this in your php files:

 <?php if (is_user_logged_in()) : ?>  
   <a href="<?php echo wp_logout_url(get_permalink()); ?>">Logout</a>  
 <?php else : ?>  
   <a href="<?php echo wp_login_url(get_permalink()); ?>">Login</a>  
 <?php endif;?>  

To add the login/register/password recovery form to your content with shortcodes, you can use the following plugin:

TDP - Frontend User Manager (http://wordpress.org/plugins/tdp-frontend-user-manager/)