How to store and receive variables in WP sessions?

I have a form with some checkboxes and inputboxes selectboxes and it shows what the user wants via an ajax call. The problem is that when the user click on the item and the detail page is shown and then decide to go back to the previous page he needs to click and select his previous choice again.

I would like to make WP to store all the options in the session when the button to the detail page is clicked and save actual info in the session and then when he visits the page again the values will be chcecked in sessions and set if any are found.

Read More

Could that be done in WP?

If yes, how?

Let’s oversimplify that and say that we have something like this in our form:

<input class="car_color" type="checkbox" name="car_color" value="1" />
<input class="car_color" type="checkbox" name="car_color" value="2" />
<input class="car_color" type="checkbox" name="car_color" value="8" />
<input class="car_color" type="checkbox" name="car_color" value="4" />
<input class="car_color" type="checkbox" name="car_color" value="6" />

I don’t use submit button in my form, it’s handled via AJAX on input change.

And in my results get via ajax I have a link to the detail page:

<a class="detail-info-link" href="<?php echo $url ?>">

Any idea how can I store my values in Session and call them when revisiting/reloading/back button in the browser?

I need to be able to read the session stored stuff and use it via ?Javascript? and trigger my search fuction via ajax which is already working well.

I just need to store (probably before going to $link in href of by detail button and read and send session variables (if they exist).

Related posts

6 comments

  1. Sessions aren’t enabled in wordpress by default, if you want to activate php sessions add this at the beginning of your functions.php:

    if (!session_id()) {
        session_start();
    }
    

    You now can use $_SESSION['your-var'] = 'your-value'; to set a session variable. Take a look at the PHP documentation on sessions.


    Update:

    There was a second answer, which, in my mind, had a value too – unfortunately it got deleted, I’m re-adding the information here. The answer was referring to WP Session Manager a plugin written by @eamann as a alternative solution.
    I read some things about the plugin, but never used it because – so far – I’m sticking with PHP sessions – never had the problem that I couldn’t use them. This is a statement/comment by the plugin author himself I found about some possible advantages.

  2. add this at in your functions.php

    <?php
    
    function tatwerat_startSession() {
        if(!session_id()) {
            session_start();
        }
    }
    
    add_action('init', 'tatwerat_startSession', 1);
    
  3. Maybe there are no usual sessions in WordPress … anyway, WordPress knows the concept of users. You can manage information related to specific users with the the functions add_user_meta, update_user_meta, get_user_meta, and delete_user_meta.

    If you need the information saved in this way in JavaScript, you can write a little PHP script that vomits what you need, and call it with Ajax.

  4. I will explain how to set a username session with the Native PHP Sessions for WordPress plugin. You can apply this logic to your problem.

    Add this to your functions.php file

    if (!session_id()) {
        session_start();
    }
    
      if ( isset( $_POST['wp-submit'] ) ){
    
        $_SESSION['username']=$_POST['log'];
    
      }
    

    $_POST[‘log’] is referencing the username input box from the wordpress login form. When a user logs in, the username is stored to $_SESSION[‘username’].
    In your case, you would change ‘log’ to the form variable names you have ‘car_color’.

    Reference the username later in some other php file by

    $username=$_SESSION['username'];
    
  5. You must first start a session in WordPress but you can’t start a session in WordPress just like that.

    Before starting sessions, you need to check if some plugin started the session earlier because you may have unexpected problems. So you need a little algorithm for that.

    if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
        if(function_exists('session_status') && session_status() == PHP_SESSION_NONE) {
            session_start(apply_filters( 'cf_geoplugin_php7_session_options', array(
              'cache_limiter' => 'private_no_expire',
              'read_and_close' => false
           )));
        }
    }
    else if (version_compare(PHP_VERSION, '5.4.0', '>=') && version_compare(PHP_VERSION, '7.0.0', '<'))
    {
        if (function_exists('session_status') && session_status() == PHP_SESSION_NONE) {
            session_cache_limiter('private_no_expire');
            session_start();
        }
    }
    else
    {
        if(session_id() == '') {
            if(version_compare(PHP_VERSION, '4.0.0', '>=')){
                session_cache_limiter('private_no_expire');
            }
            session_start();
        }
    }
    

    I’ve also added support for older PHP versions here.

  6. On the PHP page that receives the AJAX request, set $_SESSION like this.

    $car_color = <user selected form input data>;
    $_SESSION['car_color'] = $car_color;
    

    Access the $_SESSION variable

    if(isset($_SESSION['car_color'])) {
        $value = $_SESSION['car_color'];
    } else {
        $value = 'Please select a car color.';
    }
    

    This tutorial goes into more detail about proper setup and disposal of sessions.

Comments are closed.