You can create a simple logout-link like this:
<?php
$user = JFactory::getUser();
$userToken = JSession::getFormToken();
if (!$user->guest) : ?>
<a href="index.php?option=com_users&task=user.logout&<?php echo $userToken; ?>=1" class="btn">Log out</a>
<?php endif; ?>
The Log out button will only be visible to logged-in users, and when clicked the user will be logged out instantly. If you also want to show a Login button, you can modify the PHP if/else statement and display a link to the login page (index.php?option=com_users&view=login
) for guests.
<?php
$user = JFactory::getUser();
$userToken = JSession::getFormToken();
if ($user->guest) : ?>
<a href="index.php?option=com_users&view=login" class="btn">Log in</a>
<?php else: ?>
<a href="index.php?option=com_users&task=user.logout&<?php echo $userToken; ?>=1" class="btn">Log out</a>
<?php endif; ?>
The combination of PHP and HTML is necessary because we need to get the user token, without it the link will fail.
Usage:
The code can be used in several ways:
Download from GitHub
This module is available on GitHub as an installable Joomla module: https://github.com/Joomla-StackExchange/loginButton
Custom HTML
Some Custom HTML modules accept PHP code (the one included in Joomla by default does not). I recommend Custom HTML Advanced. Just paste the code and publish the module wherever you want the button to show up. Remember you can also place a module anywhere using {loadposition YourModulePosition}
.
Sourcerer
You can add PHP code anywhere using NoNumbers Sourcerer.
{source}
<?php
$user = JFactory::getUser();
$userToken = JSession::getFormToken();
if (!$user->guest) : ?>
<a href="index.php?option=com_users&task=user.logout&<?php echo $userToken; ?>=1" class="btn">Log out</a>
<?php endif; ?>
{/source}
Build a module
You can build your own module, it's easier than it sounds. A basic tutorial can be found here.
Add to your template
You can also paste the code directly into your Joomla template, usually ROOT\templates\YOURTEMPLATE\index.php
. This is the least flexible solution, but might be a quick solution depending on how your template is configured.