How can I create a custom form in WordPress? How can I create a custom form in WordPress? wordpress wordpress

How can I create a custom form in WordPress?


To answer question one: WordPress provides action and filter hooks for developers to add their custom PHP code or functions. You should look into that, because using plugins that produce snippets will not help in your case, because it causes your PHP code to execute without even loading your form, so you will be seeing your success page instead.

To learn more about action and filter hooks visit here.

Alternatively to us action/filter hooks, you can upload your PHP file into the theme folder. However, there's a flaw to that. Your file may be lost when WordPress updates.


To answer question two: There is an easier way to validate your form if using JavaScript. All you need to do is add the word 'required' within the input tag. You can also use input type 'email' together with the required keyword to validate you email. See the example below.

<form name="myForm" method="POST" action="../process.php">    Your Name: <input id="customer_name" name="customer_name" type="text" required/>    Your Email: <input id="customer_email" name="customer_email" type="email" required/>    Sex: <input name="customer_sex" type="radio" value="male" />Male <input name="customer_sex" type="radio" value="female" />Female    Your Age: <input id="customer_age" name="customer_age" type="text" />    <input type="submit" value="Submit" /></form>

If you still want to use your JavaScript function, try using document.getElementById('customer_name') and document.getElementById('customer_email') instead of document.forms. Also make sure you close your script tag at the end. See below for an example.

<script type="text/javascript">    function form_validation() {        /* Check the Customer Name for blank submission */        var customer_name = document.getElementById('customer_name').value;        if (customer_name == "" || customer_name == null) {            alert("Name field must be filled.");            return false;        }        /* Check the Customer Email for invalid format */        var customer_email = document.getElementById('customer_email').value;        var at_position = customer_email.indexOf("@");        var dot_position = customer_email.lastIndexOf(".");        if (at_position < 1 ||            dot_position < at_position + 2 ||            dot_position + 2 >= customer_email.length) {            alert("Given email address is not valid.");            return false;        }    }</script>