Skip to content

Instantly share code, notes, and snippets.

@wpexplorer
Created September 15, 2013 20:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wpexplorer/6574282 to your computer and use it in GitHub Desktop.
Save wpexplorer/6574282 to your computer and use it in GitHub Desktop.
Simple WordPress login/logout shortcode
if ( ! function_exists('wpex_loginout_shortcode') ) {
function wpex_loginout_shortcode( $atts ) {
extract( shortcode_atts( array(
'login_url' => wp_login_url(),
'log_in_text' => __( 'log in', 'wpex' ),
'log_out_text' => __( 'log out', 'wpex' ),
), $atts ) );
if ( is_user_logged_in() ) {
$url = wp_logout_url( home_url() );
return '<a href="'. $url .'" title="'. $log_out_text .'">'. $log_out_text .'</a>';
} else {
$url = $login_url;
return '<a href="'. $url .'" title="'. $log_in_text .'">'. $log_in_text .'</a>';
}
}
add_shortcode( 'loginout-link', 'wpex_loginout_shortcode' );
}
@Nodws
Copy link

Nodws commented Apr 2, 2020

Simpler if we dont care about labels

add_shortcode('login',function(){
   $url = wp_login_url();
		if ( is_user_logged_in() ) {
			$url = wp_logout_url( home_url() );
			return "<a href='$url'> Logout</a>";
		} else {		
			return "<a href='$url'>Login</a>";
		}
});

@sobhy0101
Copy link

will this ask for confirmation?

@wpexplorer
Copy link
Author

@sobhy0101 - All this does is create a link to the WordPress login page if you want logout confirmation you need to hook into the WordPress action that runs before logging out to create such confirmation. I'm sure there are plugins out there that do this.

@sobhy0101
Copy link

Sorry for not being clear before. Will this logout asks for a confirmation before redirecting to the URL?

@wpexplorer
Copy link
Author

@sobhy0101 - No, because WordPress doesn't have any confirmation built-in by default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment