0

I'm using sessions in wordpress but I have a problem where a variable I store keeps getting reset everytime I change page. it's "d_curr" and my code is the following :

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

    function myStartSession() {
        if(!session_id()) {
            session_start();
            $_SESSION['d_curr'] = 'USD';
        }
    }

    function myEndSession() {
        session_destroy ();
    }


    function process_post() {
        if( get_query_var('d_curr', 'same') != 'same' ) {
             $_SESSION['d_curr'] = get_query_var('d_curr', 'GBP');
        }
    }

I manage to change d_curr using the address bar, but everytime I change the page it gets reset to 'USD'

  • 1
    If the user is logged in why not use user meta instead? PHP Sessions don't interact well with caching systems and don't work on all server configurations, e.g. you'll get weird behaviour on WP Engine using PHP sessions – Tom J Nowell Sep 28 '17 at 15:53
  • Also get_query_var isn't a replacement for $_GET, query variables are what're passed into the main WP_Query via rewrite rules, and they have a whitelist – Tom J Nowell Sep 28 '17 at 15:53
  • Also, your query var will always get changed to GBP, the logic in process_post is broken. Those are also super generic function names, they should be prefixed – Tom J Nowell Sep 28 '17 at 15:55
  • Thanks for the comments ! You advised to use metadata for the logged-in user, but I do not plan to log them in (i.e. ID/password), will it still work ? I'm just trying to keep track of user preferences, such as their language, for the duration of the session. – An intern has no name Sep 28 '17 at 16:50
  • A logged in user doesn't have to be in the WP Admin area, they're still a logged in user, else none of the hooks you mentioned in your code would fire, wp_login will only fire if you log in. Perhaps you would be better off just using cookies – Tom J Nowell Sep 29 '17 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.