How to save data from frontend in WordPress

1) Create a Custom Post type Form

i)  The custom post type should have slug name “form”
ii) Create custom meta with slug “name”, “email”, “phone”
ii) For message we can use the default field for Post description to display our message field.

2) Form HTML in Frontend

<form id="wpform" method="POST" action="<?php echo get_permalink(get_page_by_path('contact-thankyou')); ?>">
<input type="text" name="name" id="name" placeholder="Name" class="required">
<input type="email" name="email" id="email" placeholder="Email" class="required email">
<input type="tel" name="phone" id="phone" placeholder="Phone Number" class="required number">
<textarea name="msg" id="msg" placeholder="Type message" class="required"></textarea>

<input type="hidden" name="page" id="page" value="contact">
<input type="submit" name="submit" id="contact-form-submit" class="button" value="Submit">

3) In functions.php

if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['page'] ) && $_POST['page'] == 'contact' ) {

$post_type = 'form'; // Need to create new custom type name form

$name         = $_POST['name'];
$email        = $_POST['email'];
$phone        = $_POST['phone'];
$msg          = $_POST['msg'];

//the array of arguements to be inserted with wp_insert_post
$new_post = array(
'post_title'    => "Contact - ".$name,
'post_content'  => $msg,
'post_status'   => 'publish',
'post_type'     => $post_type

//insert the the post into database by passing $new_post to wp_insert_post
//store our post ID in a variable $pid

$pid = wp_insert_post($new_post);

//we now use $pid (post id) to help add out post meta data

add_post_meta($pid, 'name', $name, true);
add_post_meta($pid, 'email', $email, true);
add_post_meta($pid, 'phone', $phone, true);


4) Buy me a coffee

Featured Cover Image Source