wp_loginout()WP 1.5.0

Outputs a "login" link if the user is not authenticated and a "logout" link if authenticated.

The additional parameter $redirect allows specifying the page to return to after login/logout.

1 time — 0.000138 sec (fast) | 50000 times — 3.67 sec (fast) | PHP 7.0.2, WP 4.4.2
Hooks from the function

Returns

null|String. Displays the ready login/logout link on the screen. If the $echo parameter is set to 0, the result will be returned for processing.

Usage

<?php wp_loginout( $redirect, $echo ); ?>
$redirect(string)
URL to redirect to after login/logout (added in version 2.8).
Default: ''
$echo(boolean)
Display on screen (1) or return for processing (0).
Default: 1

Examples

0

#1 Basic usage:

wp_loginout();

// <a href="http://example.com/wp-login.php?action=logout&_wpnonce=3bd3336222">Log Out</a>
0

#2 Add Log In/Out link to nav menu

Simply add this code to your parent or child themes functions.php file to display a Log In/Out link in the secondary navigation menu of the Twenty Fourteen default theme for WordPress.

add_filter( 'wp_nav_menu_secondary_items','wpdocs_loginout_menu_link' );

/**
 * Append Login In/Out link to menu with a redirect to this page
 */
function wpdocs_loginout_menu_link( $menu ) {

	$loginout = wp_loginout( $_SERVER['REQUEST_URI'], false );
	$menu .= $loginout;

	return $menu;
}

Other themes like Twenty Thirteen may require you to add a class to the code like this example.

$loginout = sprintf( '<li class="nav-menu" class="menu-item">%s</li>',
	wp_loginout( $_SERVER['REQUEST_URI'], false )
);

Notes

  • Uses filter 'loginout';
  • Uses: is_user_logged_in()
  • Uses: wp_login_url() and wp_logout_url()

Changelog

Since 1.5.0 Introduced.

wp_loginout() code WP 6.9.1

function wp_loginout( $redirect = '', $display = true ) {
	if ( ! is_user_logged_in() ) {
		$link = '<a href="' . esc_url( wp_login_url( $redirect ) ) . '">' . __( 'Log in' ) . '</a>';
	} else {
		$link = '<a href="' . esc_url( wp_logout_url( $redirect ) ) . '">' . __( 'Log out' ) . '</a>';
	}

	if ( $display ) {
		/**
		 * Filters the HTML output for the Log In/Log Out link.
		 *
		 * @since 1.5.0
		 *
		 * @param string $link The HTML link content.
		 */
		echo apply_filters( 'loginout', $link );
	} else {
		/** This filter is documented in wp-includes/general-template.php */
		return apply_filters( 'loginout', $link );
	}
}