how to create and show sessions in word press?

TomC is right, but to build on that here’s what I do. Mainly I use this with a global object which I serialise into the session to save and unserialise from the session to use. Here I’ve just used an array of your variables. This way you don’t need to worry about saving into the session as you go and the session use is easily expanded for other data.

My main use is for shopping baskets and orders, so proper sanitisation, validation and nonces are important, but they are left out here to keep the examples clean. See https://developer.wordpress.org/plugins/security/nonces/ and https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data

Assuming this is all going into your theme, you have init code similar to TomC’s in functions.php

add_action( 'init', 'setup_session' );

function setup_session() {

    session_start();
    global $map_data;

    if (isset($_SESSION['map_data'])) {
        $map_data = unserialize($_SESSION['map_data']);
    } else {
        $map_data = array();    
    }

    process_get();
    /* chain it after session setup, but could also hook into
       init with a lower priority so that $_GET always writes
       over older session data, or put your own action here to
       give multiple functions access to your sessions
    */
}

add_action( 'shutdown', 'save_session' ); 

function save_session() {

    global $map_data;
    if (isset($map_data)) {
        $_SESSION['map_data'] = serialize($map_data);
    }

}

function process_get() {

    // do modify this to:
    // check nonce
    // sanitise
    // validate

`   global $map_data;

    if ( isset($_GET["pickup"]) || isset($_GET["pickupadd"]) ||  isset($_GET["dropoff"]) || isset($_GET["dropoffadd"]) || isset($_GET["km"])  
 ) {
    $map_data["pickup"] = $_GET["pickup"];
    $map_data["pickupadd"] = $_GET["pickupadd"];
    $map_data["dropoff"] = $_GET["dropoff"];
    $map_data["dropoffadd"] = $_GET["dropoffadd"];
    $map_data["km"] = $_GET["km"];
}
// if any of these $_GET vars is set, replace the whole array


}

You’re also right that this could go into your template files as long as you start your session before PHP sends out the headers. In a well written theme (and assuming you aren’t running any poorly written plugins) anywhere before your HTML tag will work. Hooking into WP actions is a bit more robust in this regard, but putting the $_GET processing into a template would let you easily keep it to one page instead of running it on all of them.

You can go a step further, though this may be more effort than you need in your case, and use custom session code: https://pippinsplugins.com/storing-session-data-in-wordpress-without-_session/

Leave a Comment