In this WordPress ajax tutorial we are going to learn how to insert data using ajax in WordPress theme and insert data using ajax in WordPress.
Ajax simply means sending the data into the database or backed server without having to reload the page so that your visitor will not feel that they are leaving the website or the current page.
lets get started.
What are we going to do ?
- Create a form.
- Grab all the form data using jQuery and send data over ajax.
- Fetch and insert data into database from the WordPress.
Step 1: Creating a form
While submitting the form through ajax request in WordPress, it has its own way to send data over ajax and reach to the function inside your theme. And that is achieved through the URL admin_url('admin-ajax.php');
that is provided by WordPress to reach the admin part of the website securely.
If you want to read more about it, you can refer to the documentation of Ajax provided by WordPress. Paste this code wherever you want your form to be displayed. Like index.php / single.php / page.php
or even sidebar.php
. You can even keep these codes if you have some external page Template referred by the page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<div class="container"> <h1>WordPress AJAX Insert Post Demo</h1> <form id="enquiry_email_form" action="#" method="POST" data-url="<?php echo admin_url('admin-ajax.php'); ?>" enctype="multipart/form-data"> <div class="form-group"> <label for="">Enter Title</label> <input type="text" class="form-control" name="post_title" id="post_title" placeholder="Enter Title" /> </div> <div class="form-group"> <label for="">Enter Description</label> <textarea name="post_description" id="post_description" cols="30" rows="10" class="form-control" placeholder="Enter Post Description"></textarea> </div> <div class="form-group"> <button type="submit" class="btn btn-primary"><i class="glyphicon glyphicon-pencil"></i> Submit</button> </div> </form> </div> |
Step 2: Grabbing all the form data using jQuery and Sending to Server Via Ajax Request
I am using jQuery to achieve my result. You can also do this with the help of vanilla JavaScript if you want. Also take a note at the action variable inside the data object inside in the $.ajax()
function.
We are going to use that function inside the WordPress ajax function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
$("#enquiry_email_form").on("submit", function (event) { event.preventDefault(); var form= $(this); var ajaxurl = form.data("url"); var detail_info = { post_title: form.find("#post_title").val(), post_description: form.find("#post_description").val() } if(detail_info.post_title === "" || detail_info.post_description === "") { alert("Fields cannot be blank"); return; } $.ajax({ url: ajaxurl, type: 'POST', data: { post_details : detail_info, action: 'save_post_details_form' // this is going to be used inside wordpress functions.php }, error: function(error) { alert("Insert Failed" + error); }, success: function(response) { alert("Insert Success" + response); } }); }) |
Now once you click submit data is sent over to the ajax and we need to grab the values inside our theme functions.php
using ajax function of WordPress.
Step 3 : Fetch and Insert Data into Database from the WordPress
let’s write WordPress ajax function to grab the data and insert into database.
1 2 |
//Saving Ajax Data add_action('wp_ajax_nopriv_save_post_details_form','save_enquiry_form_action'); |
If you have just noticed the ajax function of WordPress the first argument inside the add_action function there is wp_ajax_nopriv_save_post_details_form
This string consists two main parts which is nopriv
and save_post_details_form
.
If you use nopriv in the code that means ajax will fail if the user is logged in. If the user is not logged in then only the ajax trigger works.
While the other save_post_details_form is the action that we have wrote on our JavaScript code inside the $.ajax()
inside the data object. It should be matched properly else the function won’t work.
The second argument inside the add_action
function is the name of function that we are going to use to grab the data and do what ever we want and lastly, return action true or false depending in our result and display to the user in the front end.
Lets write one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function save_enquiry_form_action() { $post_title = $_POST['post_details']['post_title']; $post_description = $_POST['post_details']['post_description']; $args = [ 'post_title'=> $post_title, 'post_content'=>$post_description, 'post_status'=> 'publish', 'post_type'=>'post', 'post_date'=> get_the_date() ]; $is_post_inserted = wp_insert_post($args); if($is_post_inserted) { return "success"; } else { return "failed"; } } |
If you want to customize the message and display the different output and if , else condition will do the trick inside the ajax and you can make our outcome message more descriptive.
This is it for the WordPress ajax form submit example. If you have any problem, you can contact us via contact form or mention them in comments.
Kumar Muthaiah says
Where to put the files ? That you missed? I always see articles in online with missing information so that user need to delay his or her work!
SNK says
Put it inside
wp-content/themes/yourtheme/functions.php
. It is the common knowledge that you require to know some of the things before using the CMS platform. All the things inside the theme file go throughfunctions.php
. Please read the documentation first at least before using any CMS.kumar muthaiah says
I need complete steps to do add/update/delete/view from a table in word press page. I use elementor plugin. I’m a wordpress beginner. I need to make sure the elementor ui is there too, i don’t want my own custom ui.
SNK says
I haven’t created tutorials on all insert add update delete view in WordPress. That will be a good idea. I will work on it.
Waldek says
It’s weird:
$is_post_inserted = wp_insert_post($args);
The
wp_insert_post
method returns an error or on success theID
of the created post. Maybe it’s better to do something like this (I think aloud – pseudocode):$is_post_inserted = is_numeric(wp_insert_post($args)) ? true : false;
SNK says
No it isn’t. I really haven’t noticed on other languages but if you insert the data into database using
wp_insert_post($args)
it will return either0
or1
. So, in php if you checkif(0)
it is always false and either is true. However, the one you suggested is the better approach which is used nowadays.