I am creating my first WordPress plugin, in which i need to restrict my customer's (site owner's) access to some of the plugins submenu pages. To do so I created a sort of a login system, where after I install the plugin i create a password and save it to the database using:
add_option('ibsupport_password', password_hash($password_new, PASSWORD_DEFAULT), '', 'yes' );
After that I present the login screen and if the password matches the one, created earlier, I use the code below to sort of hold the login session.
add_option( 'ib_logged_in', "true", '', 'yes' );
Up to this point everything works, but the problem arises when I try to create a logout button, the idea is when you click it, it runs a javascript function, that has PHP code, which deletes the 'ib_logged_in' option from the database, thus ending the login session. Here is the code:
<?php
$logged_in = (get_option('ib_logged_in', null) !== null);
if($logged_in){
?>
<button class="logout" target='blank' onClick="window.location.reload();">Logout</button>
<script>
//logout functionality
let logout = document.querySelector('.logout');
logout.addEventListener('click', handleClick);
function handleClick() {
<?php
delete_option('ib_logged_in');
?>
}
</script>
<?php
}
?>
However the delete_option('ib_logged_in'); seems to run without me clicking on the Logout button. It runs when I enter the submenu page, which has the Logout button. So the first time I enter the page the logout button is displayed, but when I refresh the page, the Logout button dissapears and (ib_logged_in) option is deleted from the database.
I am fairly new to WordPress and PHP so maybe I am missing something simple here? Is there something fundamental that I do not know about php code running in javascript functions?
Thank you for any help!