0

I'm trying to check if the user is logged in or not (in the header of the page), so I can decide if I count that user in Google Analytics or not. All I need is a true or false (0/1) from that function, but I am not sure how to properly call it within JS.

You can ignore the part within the IF blocks, it's just a dataLayer push so I can later use the value for triggering the Google Analytics tags accordingly.

So far I tried these options but without luck:

   var logintemp=0;
   logintemp=<?php echo is_user_logged_in() ?> ;

       if (logintemp) {
       window.dataLayer = window.dataLayer || [];
       window.dataLayer.push({
       'userLoggedIn' : '1'
       });} 
       
       else {
       window.dataLayer = window.dataLayer || [];
       window.dataLayer.push({
       'userLoggedIn' : '0'
       });}
</script>
<script type="text/javascript">
        if ('<?php is_user_logged_in(); ?>') {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
        'userLoggedIn' : '1'
        });} 
        
        else {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
        'userLoggedIn' : '0'
        });}
</script>```
3
  • This is a duplicate question, you can see answers here: wordpress.stackexchange.com/questions/69814/… Commented Apr 13, 2022 at 17:47
  • I still cannot manage to make any of these work /: Commented Apr 13, 2022 at 18:08
  • @BackY Then please add more information to the question explaining what you have tried and what the actual behavior was along with any error messages or unexpected generated JavaScript. Commented Apr 15, 2022 at 12:46

3 Answers 3

1

Echoing a FALSE in PHP doesn't print anything to the screen. This is why your first example didn't work and it produced invalid JS when the user wasn't logged in.

logintemp= ;

A simple way to do this is to make sure you json_encode the server side data so the JS can access it. Since JSON is a subset of JS, it will properly escape any content and produce a valid expression that can be assigned to a variable.

var isLoggedIn = <?php echo json_encode(is_user_logged_in()) ?>;

if (isLoggedIn) {
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    'userLoggedIn': '1'
  });
} 
   
else {
   window.dataLayer = window.dataLayer || [];
   window.dataLayer.push({
     'userLoggedIn': '0'
   });
}

And the above can be simplified to

var isLoggedIn = <?php echo json_encode(is_user_logged_in()) ?>;
window.dataLayer = window.dataLayer || [];      
window.dataLayer.push({
   userLoggedIn: isLoggedIn ? '1' : '0'
});
   

See Variable from html to javascript

Generating JavaScript from PHP

Dynamically generated code, as suggested by @Clarus Dignus, makes it much harder to read and maintain the code as you try to align code within both environments.

Having a single place where all the server side data drives the code makes it a lot easier to debug the code since the JavaScript code itself is not changing, just a value.

Sign up to request clarification or add additional context in comments.

Comments

-1

All you need is an endpoint that will return 1 if the user is logged in, otherwise 0.

let XHR = new XMLHttpRequest();
XHR.open( 'GET', '/yourEndPoint' );

XHR.onreadystatechange = function() {
   if (this.status == 200) {
       window.dataLayer = window.dataLayer || [];
       window.dataLayer.push({
           'userLoggedIn' : XHR.responseText
       });
       //Do something else here
   }
};

XHR.send();

4 Comments

Will this work if I executed it from Elementor's custom code pannel? I can pick for this code to be executed in the <head> but not exactly where, probably before the closing </head> tag. Regarding the endPoint, I'm not sure I understand what I am supposed to replace this value with. I'm sorry for my rookie question but I am not very advanced with coding.
You can see this link for more information. I hope it will help you.
Thanks Metehan! Unfortunately I tried a few methods there but nothing helps :(
This is adding an API endpoint that is not really required. There's no need to completely rework the solution. You also should be using fetch in your examples since its API is much simpler.
-1

@Clarus Dignus at the Wordpress-Org forum offered a nice solution via a plugin that makes sure the header code is executed in the header. He first asked me to execute this, to confirm everything is working:

<?php
if ( is_user_logged_in() ) {
    echo 'Welcome, registered user!';
} else {
    echo 'Welcome, visitor!';
}
?>

Then I used his solution to do the dataLayer push and works perfectly!:

<?php
if ( is_user_logged_in() ) {
?>
<script>
//Your JavaScript for when user is logged in
</script>
<?php
} else {
?>
<script>
//Your JavaScript for when user is logged out
</script>
<?php
}
?>

The plugin I used for the code insertion: Head, Footer and Post Injections plugin.

5 Comments

This answer does not show that you understood what the problem was, you were given an answer that works and you are not sure why. This solution takes more code; your initial direction was easier to follow, you just didn't realize that echo FALSE doesn't print anything to the screen. It looks like you didn't analyze the generated HTML/script tag enough to see what was happening.
As I said, I am not very advanced at coding.
Which is why I took my time to write a detailed explanation to help you 👍🏽
Tried your code again, and it doesn't work, unfortunately. I am not gonna invest any more time to investigate why it's working or why it didn't work before. I will do that when I have the time, or the desire. Thank you very much for your effort again, I appreciate the time.
Just saying "it doesn't work" without explaining what happened does not benefit anyone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.