1

I want to add session and retrieve value from it in wordpress. I am using subdomain for my website. I have added code in header.php file of a theme to retrive a subdomain and put it in session. I have started session and put the value in it. When I use subdomain in url session retrives session value but without subdomain name, it doesn't works, even session have that value. Following are my code:

$url = $_SERVER['SERVER_NAME'];
$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['path']);
$subdomain = $host[0];

$wp_session = WP_Session::get_instance();
if(isset($wp_session['user_subdomain']))
{
?>
<script>alert('<?php echo "Check first session Set ".$wp_session['user_subdomain']; ?>');</script>
<?php
}
else
{
?>
<script>alert('<?php echo "Check first session Not Set "; ?>');</script>
<?php
}
if($wp_session['user_subdomain']=="test"){
?>
<script>alert('<?php echo "session ".$wp_session['user_subdomain']; ?>');</script>
<?php
$red_url=$wp_session['user_subdomain'].".domain.com";
?>
<script>alert('<?php echo "RED ".$red_url; ?>');</script>
<?php
header("location:$red_url");
}
else if($subdomain=="test"){
$red_url=$_SERVER['SERVER_NAME'];
$wp_session['user_subdomain']=$subdomain;
?>
<script>alert('<?php echo "get ".$subdomain; ?>');</script>
<script>alert('<?php echo "check set session ".$wp_session['user_subdomain']; ?>');</script>
<?php
header("location:$red_url");

}

I have added '_SESSION' in wp_unregister_GLOBALS function, I found it somewhere on google.

vishal
  • 27
  • 8

2 Answers2

0

You have to set session id on subdomain too.

Try to add this line

ini_set('session.cookie_domain', '.example.com' );

More info

Community
  • 1
  • 1
Divyesh Savaliya
  • 2,692
  • 2
  • 18
  • 37
  • Thanks @Divyesh My code is working but only for IE. not working on chrome and firefox. – vishal Jun 20 '16 at 09:44
  • when page refresh page don't alert session value. if we use session(); function only and set session. Session destroy on page load. Why its happing? – vishal Jul 05 '16 at 10:45
0

We give priority to set session. The following code will works fine.

add_action('init', 'myStartSession', 1);

function myStartSession() {
    if(!session_id()) {
        session_start();
    }
}
vishal
  • 27
  • 8