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
Answers
@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:
Then I used his solution to do the dataLayer push and works perfectly!:
The plugin I used for the code insertion: Head, Footer and Post Injections plugin.
All you need is an endpoint that will return
1
if the user is logged in, otherwise0
.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.
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.And the above can be simplified to
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.