Skip to content

Instantly share code, notes, and snippets.

@danmaby
Created September 28, 2023 10:38
Show Gist options
  • Save danmaby/c13ab974b03176eaeca81f855e60f811 to your computer and use it in GitHub Desktop.
Save danmaby/c13ab974b03176eaeca81f855e60f811 to your computer and use it in GitHub Desktop.
Simple log in / log out shortcode for WordPress. Conditionally display a login or logout text link based on users logged in status.
<?php
/**
* Shortcode to display "Log in" or "Log out" link.
*
* @return string HTML string for the login/logout link.
*/
function dm_login_logout_shortcode() {
// Initialize an empty string to hold the output HTML.
$output = '';
// Check if the user is logged in.
if ( is_user_logged_in() ) {
// If the user is logged in, display the "Log out" link.
$logout_url = wp_logout_url( home_url() ); // Home URL can be replaced with a custom URL.
$output = "<a href='{$logout_url}'>Log out</a>";
} else {
// If the user is not logged in, display the "Log in" link.
$login_url = wp_login_url( home_url() ); // Home URL can be replaced with a custom URL.
$output = "<a href='{$login_url}'>Log in</a>";
}
return $output;
}
// Register the shortcode.
add_shortcode( 'dm_login_logout_link', 'dm_login_logout_shortcode' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment