WooCommerce Logout PHP Snippet to Create Logout Button

WooCommerce Logout PHP SnippetIn my previous blog post on how to remove the WooCommerce logout confirmation message, I shared the quick snippets you can use to remove that persistent message seen when the customer logs out of WooCommerce. Today, I want to quickly share the WooCommerce logout PHP snippet that you can use to create a logout button on your WooCommerce theme template or you can add in a shortcode action to create a WooCommerce logout shortcode.

WooCommerce Logout PHP Snippet

This is a very useful WooCommerce snippet that you can use in your day to day WooCommerce theme or plugin development.

Ideally, the WooCommerce logout PHP snippet comprises of the default WordPress logout function outlined below :

wp_login_url( string $redirect = ''bool $force_reauth = false )

The function has two parameters

Parameter Description
$redirect (string) (Optional) Path to redirect to on login.
$force_reauth  (bool) (Optional) Whether to force reauthorization, even if a cookie is present.

To create the logout URL you can use the function as in the code snippet below :

<?php if (is_user_logged_in()) : ?>
<a href="<?php echo wp_logout_url(get_permalink()); ?>">Logout</a>
<?php endif;?>

If you just want to add a logout button in your WooCommerce theme template, you can simply add this code in the template and the logout link will appear. You can wrap the a href tag with a <button> tag and style the logout button appropriately.

Page Redirect (Internal)  After WooCommerce Logout

The code snippet contains the redirect URL after log out and you can pass the page ID in the get_permalink() function to the page where you want the user to be redirected after logout.

External URL Redirect After WooCommerce Logout

If you prefer customers to be redirected to some external URL after they log out, you can consider adding the external URL on the code as shown on the code below :

wp_logout_url( 'http://example.com' );

If you want to create a shortcode button for the WooCommerce logout, I created an elaborate tutorial on how to create a WooCommerce logout shortcode that is an excellent guide.

Similar Articles

Comments are closed.