How to submit the form in WordPress
Today, We will learn How to submit the form in WordPress. WordPress has default a generic handler to deal with all forms in admin-post.php
. When we submit the form on our WordPress website, we need to include a hidden field in a form called action
.
Example
index.php
<?php
$html = "<form method='post' action='".get_admin_url()."admin-post.php'>
<input type='hidden' name='action' value='submit-form'/>
<input type='hidden' name='redirect_url' value='".$_SERVER['REQUEST_URI']."'/><fieldset>
<div class='name field text_field' id='field-name'>
<label class='field-label'>Your Name*</label>
<input type='text' name='name' required placeholder='Your Name*' />
</div>
<div class='phone field text_field' id='field-phone'>
<label class='field-label'>Phone</label>
<input type='text' name='phone' required class='plain-phone' placeholder='Phone' />
</div>
<div class='email field email_field' id='field-email'>
<label class='field-label'>Email*</label>
<input type='email' name='email' required placeholder='Email*' />
</div>
<div class='url field text_field' id='field-url'>
<label class='field-label'>URL</label>
<input type='text' name='url' placeholder='URL' />
</div>
<div class='message field text_area' id='field-message'>
<label class='field-label'>Message</label>
<textarea name='message' placeholder='Message'></textarea>
</div>
</fieldset>
<div class='footer'>
<input type='submit' name='submit' value='Send Message' />
</div>
</form>";
return $html;
functions.php
<?php
add_action('admin_post_registration-form', '_handle_form_action'); #If the user is logged in
add_action('admin_post_nopriv_registration-form', '_handle_form_action'); #If the user in not logged
function _handle_form_action(){
global $wpdb;
session_start();
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$message = $_POST['message'];
$redirect_url = $_POST['redirect_url'];
$admin_email = 'info@devnote.in';
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$data = "<b>Name</b>: $name \r\n <b>Phone</b>: $phone \r\n <b>Email</b>: $email \r\n <b>Message</b>: $message";
$mail = wp_mail($admin_email, "Your subject here!", $data);
if($mail) {
wp_redirect(home_url('/').$redirect_url.'/?status=1');
} else {
wp_redirect(home_url('/').$redirect_url.'/?status=0');
}
die();
}