• I’m trying to extend my child theme’s functions.php with a handler for an AJAX call:

    $selection_has_changed = function () {
        check_ajax_referer( ACTION_NAME );
    
        $email = $_POST['email'];
        $checked = $_POST['checked'];
    
        $bulk_recipients[$email] = $checked;
        echo json_encode($bulk_recipients);
    
        die();
    };

    Just adding or updating a key-value pair to global dict $bulk_recipients.

    The dict is defined at the top of functions.php like so:

    $bulk_recipients = [];

    After much testing I find that $bulk_recipients seems to be reset each time it enters $selection_has_changed. Ie it only ever outputs 1 key-vaue pair.

    Is there some WordPress “magic” afoot causing this behavior?

    Could it be an issue with functions.php lifecycle?

    I’m a beginner dev in WordPress and PHP so sorry if this is a naive question.

    TIA.

    • This topic was modified 1 year, 10 months ago by ingridskard.
    • This topic was modified 1 year, 10 months ago by ingridskard.

    The page I need help with: [log in to see the link]

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    Every Ajax request is a new request where all vars are initialized anew. If you need a value to persist between requests it needs to be saved somewhere. The options are:
    Keep track of it by passing the current value as an URL query string.
    Save it in a cookie.
    Save it in the DB, for example as a transient.
    Save it as a session var. Session vars in WP can cause issues if not implemented correctly. As a beginner, you may want to avoid this.

    Thread Starter ingridskard

    (@ingridskard)

    Thank you so much for the info and tips! Surprising to hear functions.php is initialized anew on each AJAX call, if I’m understanding you correctly.

    I’m thinking to make a custom plugin to store the global in, if I can’t put it in a session var as the ideal solution would have one global per session. Thanks again!

    Moderator bcworkz

    (@bcworkz)

    You’re welcome. Not only is functions.php executed anew with every Ajax request, the entire WP environment is initialized anew for every HTTPS request of any kind. If you’re curious about the nitty gritty of what happens with a typical request, look at the query overview.

    If you choose to use session vars, be sure you properly close the session when you’re finished with it. Unclosed sessions are a large part of why people have difficulty with session vars in WP.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Global variable reset in functions.php’ is closed to new replies.