0

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!

  • Of course it doesn PHP executes the code before printing it. – biesior Aug 03 '20 at 17:47
  • What you're missing is the order of operations. Any PHP code you have there is processed *before* your Javascript is output to browser. Your JS will then only contain the resulting output from the PHP code (if any). You will want to use AJAX / Fetch instead. – Markus AO Aug 03 '20 at 17:47
  • That's because it doesn't work like that. PHP is server side. This basically means that once the page is fully loaded, the PHP is done. It doesn't do anything else, and it can't be called in JavaScript like this. If you absolutely need to call some PHP from JavaScript, use AJAX. – GrumpyCrouton Aug 03 '20 at 17:47

0 Answers0