How to create a logout URL in WordPress with wp_logout_url

The wp_logout_url function in WordPress is used to generate the URL for the logout page. This function can be useful for creating a custom logout link or button within a WordPress theme or plugin. It allows users to log out of their current session and redirect to a specific page after logging out.

By using wp_logout_url, developers can ensure that users are directed to the correct logout page and that any necessary actions, such as clearing session data or redirecting to a specific page, are handled automatically.

Parameters Accepted by wp_logout_url Function

  • $redirect (string, optional): Path to redirect to on logout. Default value is an empty string.

Value Returned by wp_logout_url Function

The function returns a string, which is the logout URL. It’s important to note that the URL is HTML-encoded via esc_html() in wp_nonce_url().

Examples

Example 1: How to create a logout URL for a WordPress site

Use the wp_logout_url function to generate a logout URL for a WordPress site.

<?php
$logout_url = wp_logout_url();
echo '<a href="' . $logout_url . '">Logout</a>';
?>

Example 2: How to redirect to a specific page after logging out

Use the wp_logout_url function to generate a logout URL and specify the redirect page.

<?php
$redirect_url = home_url( '/goodbye' );
$logout_url = wp_logout_url( $redirect_url );
echo '<a href="' . $logout_url . '">Logout</a>';
?>

Example 3: How to conditionally display the logout URL

Use the wp_logout_url function within a conditional statement to display the logout URL only if the user is logged in.

<?php
if ( is_user_logged_in() ) {
 $logout_url = wp_logout_url();
 echo '<a href="' . $logout_url . '">Logout</a>';
}
?>

Conclusion

The wp_logout_url function is a valuable tool for developers working with WordPress. It provides a simple and efficient way to create a logout URL for users, allowing for a seamless and user-friendly experience. By utilizing this function, developers can ensure that their websites maintain security and provide a smooth logout process for users. With its ease of use and practicality, the wp_logout_url function is a valuable asset for any WordPress developer.

Related WordPress Functions