Session variables

By: Sam Rossetti | Asked: 06/20/2023
ForumsCategory: General questionsSession variables
Sam RossettiSam Rossetti asked 1 year ago
Hello ! i need to store a session variable into a field. Here’s what i have but it doesn’t work, i always endup with the unknown status :  
function store_session($values){
    if( $values['form_id'] == 13){
        $session_src = 'unknown';<
        if(isset($_SESSION['source'])){
            $session_src = $_SESSION['source'];
        }
        $values['item_meta'][182] = $session_src;
    }
    return $values;
}
add_filter('frm_pre_create_entry', 'store_session');
Do you have an idea why this fails ?
Thanks for your help
1 Answers
Victor Font answered 1 year ago
Your setting a default value of "Unknown". You are also testing for isset($_SESSION['source']), If isset($_SESSION['source']) doesn't exist, you will always get the default value. You also have an error in your code. You have an angle bracket after the semicolon for your default value. Misplaced characters in your code will always ensure the code won't run correctly.
Victor Font replied 1 year ago

Where is your start_session() located? How are you populating $_SESSION['source']? When I test for the values of $_SESSION using your code in my development environment, $_SESSION is NULL. $_SESSION is not enabled unless you start and manage the $_SESSION yourself.

WordPress has "abstract class WP_Session_Tokens" you can extend to use for your own $_SESSION variables. https://developer.wordpress.org/reference/classes/wp_session_tokens/

You can also create your own $_SESSION without extending the WordPress class. https://www.php.net/manual/en/reserved.variables.session.php

Sam RossettiSam Rossetti replied 1 year ago

Hi Victor and thanks for your answer.

Sorry i wasn’t torough in my descritption, but to summarize and answer your questions :

- the session and it’s variables are declared in the WP’s header.php
- the error is a typo when i copy/pasted my function (i cleaned up some irrelevant code regarding the problem). The function runs without problem on my website.

Thanks for the reference to wp_session_tokens i think that will do the trick 🙂

Making the Best WordPress Plugin even better - Together

Take on bigger projects with confidence knowing you have access to an entire community of Formidable Experts and Professionals who have your back when the going gets tough. You got this!
Join the community
crossarrow-right