Creating forms and using filled values in WordPress

Creating forms and using filled values in WordPress

If you are new to WordPress development, creating a form in WordPress then using the filled in values to do things in your theme or plugin might be tricky. The good news is that using a form in the WordPress code is very easy and doesn’t require a plugin.

To deploy a form in a page you have 2 options:

  • create the form in a theme template (this will be hardcoded in all the pages/posts that are using that template)
  • create the form in a plugin (or in functions.php inside the theme) and use it via a shortcode in the WordPress dashboard editor (so the editor will be able to place the form in his regular content)

For this example, we are going to create a form in page.php (so it will appear in all WordPress pages, unless you do some additional code to display it in a specific page).

So, go to your theme, and look for page.php, then search the area where the content is displayed (using the_content WordPress tag) – you can place the form anywhere in the code, but let’s say you want it somewhere in the content area.

Adding a HTML form to a WordPress page

We are going to add a very basic form (but you can add more fields as you wish):

<form action="<?php esc_url( $_SERVER['REQUEST_URI'] ) ?>" method="post"  name="addmonitor">
<p>Description (optional) <br />
<input type="text" name="cf-description" value="" size="10" />
<p><input type="submit" name="cf-submitted" value="Send"/></p>

Now, the above form will display an input text field with the label “Description” and a Send button, and the action code "<?php esc_url( $_SERVER['REQUEST_URI'] ) ?>" says “send the form data to the same page”.

Now, let’s see what values does the form send? To read the HTTP POST values of a form, you need a bit of PHP code:


What this code does is it “prints” on the screen all the POST values (the <pre> tags are for nice formatting of the values).  The important things to note are that the description field will send the values that can be read as "cf-description" and the send button will be "cf-submitted". So if you read these 2 HTTP POST values you can use them further in your code.

Using the POST values

Now that we know what the form sends, we can use the values further. Try the following code:

<?php  if ( isset( $_POST['cf-submitted'] ) ) {
echo $_POST['cf-description'];
} ?>

The firs line checks if the send button has been pressed. The second line prints on the screen the filled in value for the description field. Sweet.