2

I need to conditionally show some content on a WordPress page based on session count. Basically, only show content to the visitor for his or her first 3 sessions. I don't have an analytics tag on the page so I started looking into implementing PHP session with session_start but I don't understand the conditional below as session_id is always empty in my var_dump, when I reload the page. I was going to use the conditional to generate a cookie with session count but the first var_dump always returns empty. Any ideas?

add_action('init', 'myStartSession', 1);
add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myEndSession');

function myStartSession() {
    var_dump(session_id()); //always empty 
    if(!session_id()) {
        session_start();
        var_dump(session_id()); //never empty 
    }
}

function myEndSession() {
    session_destroy ();
}
Community
  • 1
  • 1
iwek
  • 1,608
  • 5
  • 16
  • 31
  • Session Start needs to be at the top, you will only get the id after you start the session. Since you only kill the session after the user logout, you will get the same Session ID. For your system you will need to to use a different approach. – Ricardo Nuñez Dec 19 '16 at 15:16
  • Initially, I expect the first var_dump to be empty and the second one to not be empty. But, when I refresh the page, why is the first var_dump still empty? I did not login/logout, i did not do session_destroy, so why would the first var_dump be empty on page refresh? – iwek Dec 19 '16 at 15:38
  • I understand your logic, but no. Because the session only starts after the sesision_start() is called. If the session doesn't exist it will be created, if it does exist, it will retrieve the ID. – Ricardo Nuñez Dec 19 '16 at 18:15

0 Answers0