Snippets

Pavel Petrov How to redirect in WordPress after form submission

Created by Pavel Petrov
<?php
//...
function generateRandomString($length = 5)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; ++$i) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }

    return $randomString;
}
add_action('init', function() {
    if (isset($_POST["submission"])) {
        $validation = function() {
            $errors = [];
            //Validate
            //...
            return $errors;
        };
        if(empty($validation()))
        {
            $signature = generateRandomString();
            $response = [
                'success' => true,
                'message' => 'Thanks for your submission',
            ];
            set_transient($signature, $response, 10 * MINUTE_IN_SECONDS);
            global $wp;
            wp_redirect(add_query_arg('fid', $signature, home_url($wp->request).$_SERVER['REQUEST_URI']));
            exit;
        }
    }
});
1
2
3
4
5
6
7
<?php
//...
if (isset($_GET['fid'])) {
    $notification = get_transient($_GET['fid']); ?>
    //Do something with the notification 
    echo $notification['message'];
}

Comments (0)