Posting a form in WordPress

When creating a form, you typically post that form’s data to another file to process the input and do its magic. This can be difficult with WordPress because of the way it handles its data. There is a simple solution.

  1. We are going to post the form to the page it is currently on.
  2. Then we are going to add a block of code to the theme’s functions.php file
  3. When the page refreshes, this code will check if the form was submitted.

Example Form code
[php]<form action="<?php echo get_permalink( $post->ID ); ?>" method="POST" id="namespace-form">
<label>First &amp; Last Name</label>
<input type="text" name="username" id="name" value="" placeholder="First & Last Name" />
<input type="hidden" name="user_id" value="123" />
<input type="submit" value="Submit" name="submit_namespace_form" id="submit_namespace_form" />

Code block for functions.php
[php]add_action(‘init’, ‘namespace_form’);
function namespace_form(){
$user[‘username’] = sanitize_user(stripslashes($_POST[‘username’]));
$user[‘user_id’] = (is_number($_POST[‘user_id’]) ? $_POST[‘user_id’] : 0;
update_option(‘namespace_user’, $user);

I wrote this on-the-fly so it’s untested. Be sure to edit it to fit your needs.

About Clifton Hatfield

Clifton is the kind of guy that can read code better than he can read a book and prefers it that way. He likes cold pizza, moving sidewalks, and Indiana Jones. Clifton co-founded Internet Lifestyle Network from his home office in 2012 and he believes that true leadership is to inspire.

So which fields can you use on this form. Does this work like contact form? I own a WP blog and use several form plugins for this. Thanks!

Clifton Hatfield
Clifton Hatfield

This code is used to capture the form data after it has been posted.