Snippets

Pavel Petrov How to redirect in WordPress after form submission

Created by Pavel Petrov

File functions.php Added

  • Ignore whitespace
  • Hide word diff
+<?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;
+        }
+    }
+});

File single.php Added

  • Ignore whitespace
  • Hide word diff
+<?php
+//...
+if (isset($_GET['fid'])) {
+    $notification = get_transient($_GET['fid']); ?>
+    //Do something with the notification 
+    echo $notification['message'];
+}
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.