skip to Main Content

I’m trying to add a simple form to a WordPress page that would redirect to another page if the correct text is entered into the form, otherwise if incorrect text was entered it would just re-display the form.

My idea is to put the form on a page with the title ‘Members Only’ where I would ask for a street name to be entered. If someone enters "Broadway" then the form would redirect the user to a ‘Members Only Success’ page. I created a custom form handler plugin that includes a function to define a shortcode that I can use to embed the form on the Members Only page. That’s working. But I’m not sure how to get that form to call my custom_form_handler function in the plugin that contains the logic that needs to execute. I tried using the code in the first line of that function to detect if a form was submitted on a page with title Members Only, but I don’t think that’s working. Here is my current code in the plugin:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
/*
Plugin Name: Custom Form Handler
Description: Handles the custom form submission.
*/

function custom_form_handler() {
    if (isset($_POST['submit']) && is_page('Members Only')) {
        $streetName = sanitize_text_field($_POST['street_name']); // Sanitize the input.

        // Check if the "Street Name" field is valid
        if ($streetName === "Broadway") {
            // Redirect to the "Members Only Success" page.
            wp_redirect(site_url('/membersonly-success/'));
            exit();
        } else {
            // Display the form with an error message.
            echo "Invalid street name.";
            display_form();
        }
    }
}

function display_form() {
    ?>
    <form method="POST">
        Street Name <input type="text" name="street_name">&nbsp;
        <input type="submit" name="submit" value="Gooo">
    </form>
    <?php
}

add_action('template_redirect', 'custom_form_handler');

function custom_form_shortcode() {
    ob_start(); // Start output buffering.
    ?>
    <form method="POST">
        Street Name <input type="text" name="street_name"><br/>
        <input type="submit" name="submit" value="Go">
    </form>
    <?php
    return ob_get_clean(); // Return the buffered content.
}

add_shortcode('custom_form', 'custom_form_shortcode');

2

Answers


  1. WordPress has 2 hooks for form submission :

    admin_post_{$action} // for logged-in users
    admin_post_nopriv_{$action} // for non-authentificated users
    

    To call your form handler when the form is submitted, you have two things to add :

    In your form, add a hidden input with a custom action name (memberForm for the sake of the example) and make sure the form is sent to /wp-admin/admin-post.php :

    <form method="POST" action="http://www.example.com/wp-admin/admin-post.php">
     <input type="hidden" name="action" value="memberForm">
     ....
    </form>
    

    In your PHP code, you’ll need to add the two hooks :

    function custom_form_handler() {
       ...
    }
    add_action('admin_post_memberForm', 'custom_form_handler');
    add_action('admin_post_nopriv_memberForm', 'custom_form_handler');
    

    How it works is fairly simple : when admin-post.php receives a request, it checks the "action" parameter received ($_POST[‘action’]), and then, call the two hooks, replacing {$action} by the value of "action".

    The action name is of your choosing, but make sure it is unique. I’d say "memberForm" could probably be used by some other plugin.

    Here’s the pertinent documentation :

    https://developer.wordpress.org/reference/hooks/admin_post_action/
    https://developer.wordpress.org/reference/hooks/admin_post_nopriv_action/

    Login or Signup to reply.
  2. Your idea and approach are on track! You just need a few tweaks to make sure your custom_form_handler function is properly called.

    Here are the modifications to your existing plugin code:

    Change the hook from template_redirect to init for better form submission handling. In the shortcode function, first call the custom_form_handler() function to check if the form has been submitted and handle accordingly.
    Ensure that you’re using $_POST['submit'] correctly.

    The modified code should look like this:

    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    /*
    Plugin Name: Custom Form Handler
    Description: Handles the custom form submission.
    */
    
    function custom_form_handler() {
        if (isset($_POST['submit']) && is_page('Members Only')) {
            $streetName = sanitize_text_field($_POST['street_name']); // Sanitize the input.
    
            // Check if the "Street Name" field is valid
            if ($streetName === "Broadway") {
                // Redirect to the "Members Only Success" page.
                wp_redirect(site_url('/membersonly-success/'));
                exit();
            } else {
                // Display the form with an error message.
                echo "Invalid street name.";
                display_form();
                exit(); // Prevent the form below from being displayed twice
            }
        }
    }
    
    function display_form() {
        ?>
        <form method="POST">
            Street Name <input type="text" name="street_name">&nbsp;
            <input type="submit" name="submit" value="Go">
        </form>
        <?php
    }
    
    add_action('init', 'custom_form_handler'); // Changed from template_redirect
    
    function custom_form_shortcode() {
        ob_start(); // Start output buffering.
    
        custom_form_handler(); // Call the handler within the shortcode.
        display_form(); // This will display the form.
    
        return ob_get_clean(); // Return the buffered content.
    }
    
    add_shortcode('custom_form', 'custom_form_shortcode');
    

    I haven’t tested this code. So give it a try and make adjustments to it if needed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search