Skip to content

Testing Variable Update Shortcode

This is a test of updating a variable in a session. The following shortcode is used in Snippets to display the value of my_variable and to update it. 

Issues:

  • Make sure the code snippet called variable_update_shortcode is enabled before testing
  • Have to have code in theme functions php as in second code block – check whether it is uncommented in functions.php before testing it
  • Without the start session code, I can only get it to subtract from the value once
  • With start session code, it behaves sometimes erratically – sometimes it will subtract the values with multiple rapid fire button clicks, and sometimes it works if you wait a second or two between clicks. Unreliable behavior.
  • Only works for the session, so multiple users would have their own variable in their own session (not a shared variable

Test 1: Shortcode widget

Current value: 6

Test 2: Getting variable in a form

Works only when the start session code is on
				
					// Add a shortcode to handle variable setting and updating
function variable_update_shortcode() {
    // Start the output buffer
    ob_start();

    // Initialize the session variable if not set
    if (!isset($_SESSION['my_variable'])) {
        $_SESSION['my_variable'] = 6;
    }

    // Check if the form was submitted
    if (isset($_POST['update_variable'])) {
        // Subtract one from the variable
        $_SESSION['my_variable']--;

        // Ensure the variable does not go below zero
        if ($_SESSION['my_variable'] < 0) {
            $_SESSION['my_variable'] = 0;
        }
    }

    // Display the form and the variable
    ?>
    <form method="post" action="">
        <p>Current value: <?php echo $_SESSION['my_variable']; ?></p>
        <button type="submit" name="update_variable">Subtract One</button>
    </form>
    <?php

    // Get the output buffer content and clean it
    return ob_get_clean();
}

// Register the shortcode with WordPress
add_shortcode('variable_update', 'variable_update_shortcode');

				
			
				
					/* Added to theme functions.php to test a session variable
*/
function start_session() {
    if (!session_id()) {
        session_start();
    }
}
add_action('init', 'start_session');