How To Insert Custom Logout Function in WordPress Menu with JavaScript
This is a simple way for you to add a custom code to create a logout in which you are going to change the text in Menu and Put Logout, that way you have a logout functionality. best solution incase you have a membership site, or Wocoomerce website.
1. You just basically add a menu and get the ID which hold that menu you add, in this case this menu on the screenshot provided above is #menu-item-3117, then since menu is a link you should also include the a tag for you to select that id in JavaScript.
2. Next is Install Code Snippet Plugin and copy the code provided below.
add_action('wp_footer', function() {
if ( is_user_logged_in() ) {
$logout_url = wp_logout_url(); ?>
<script>
const loginLogoutLink = document.querySelector('#menu-item-3117 a');
loginLogoutLink.innerHTML = 'Logout';
loginLogoutLink.addEventListener('click', function(event) {
event.preventDefault();
window.location.href = '<?php echo esc_js($logout_url); ?>';
});
</script>
<?php }
});
Take note that you need to use the PHP Snippet if you are using a code snippet plugin "WPCode Lite" WPCode.
After you copy this will now work, also if you encountered problems you might need to clear cache, hope this helps and happy coding.
Post a Comment