I want to show a popup to the first time visitor of a Wordpress site. I tried to check the visit state using $_SESSION
. Something like this in the footer.php:
<?php
if(!isset($_SESSION['pxpop']))
$_SESSION['pxpop']= true;
if(($_SESSION['pxpop']) && (!is_user_logged_in()))
{
?>
<div class="open_initpop">
<?php if(is_active_sidebar('msg-pop')): ?>
<?php dynamic_sidebar('msg-pop'); ?>
<?php endif; ?>
</div>
<?php
$_SESSION['pxpop']= false;
}
?>
with session_start();
in the init
hook of the functions.php.
But this is not working. $_SESSION['pxpop']
remains true
on each page load. So the popup opens on each page.
With a little r&d I have found that due to some 'statelessness' issue wordpress does not use sessions. From the site health section, it also says:
"PHP sessions created by a session_start() function call may interfere with REST API and loopback requests. An active session should be closed by session_write_close() before making any HTTP requests."
Then I tried implementing $_COOKIE
too (in the init
hook) as:
<?php
function pop_event()
{
if(!isset($_COOKIE['pxpop']))
{
setcookie('pxpop', true, 0);
//$_COOKIE['pxpop']= true;
}
if(($_COOKIE['pxpop']) && (!is_user_logged_in()))
{
?>
<div class="open_initpop">
<?php if(is_active_sidebar('msg-pop')): ?>
<?php dynamic_sidebar('msg-pop'); ?>
<?php endif; ?>
</div>
<?php
//unset($_COOKIE['pxpop']);
//$_COOKIE['pxpop']= false;
setcookie('pxpop', false, 0);
}
}
?>
But this is not working too...
What is wrong with my approach? What is the correct way to carry forward a value in Wordpress like PHP session without actually using it? Or using $_SESSION is the only resort?