How to Upload Images in a Custom Page Using AJAX in WordPress
As a WordPress developer, you may often find the need to allow users to upload images in a custom page. This can be a common requirement for applications that require users to submit documents or proof of identity. In this blog post, we'll explore how to create a function in the functions.php file to handle AJAX image uploads in a custom WordPress page.
Understanding the AJAX Call
Let's start by understanding the AJAX call that we'll be using to handle the image uploads. The provided code snippet is as follows:
$("#YourButtnID").click(function(){
var firstname = $('#fname').val();
var identity = jQuery('#identity').prop('files')[0];
var residence = jQuery('#residenceID').prop('files')[0];
var selfie = jQuery('#selfie').prop('files')[0];
var formData = new FormData();
formData.append('action','your_custom_function');
formData.append('fname',firstname);
formData.append('identity', identity);
formData.append('residence', residence);
formData.append('selfie', selfie);
$.ajax({
type: "POST",
url: ajaxurl,
contentType: false,
processData: false,
data: formData,
dataType: "JSON",
success:function(data){
if(data['status']){
//All went well
}else{
// something went wrong
}
},
error:function(err){
// You might not have caught any exception
}
});
});
In this AJAX call, we're first getting the values of the form fields, including the first name and the three image files (identity, residence, and selfie). We then create a FormData object and append the necessary data, including the action
parameter, which will be the name of the custom function we'll create in the functions.php file.
The AJAX call is made to the ajaxurl
variable, which is a WordPress-specific variable that points to the AJAX endpoint. We set the contentType
and processData
options to false
to allow the FormData object to be sent correctly. Finally, we handle the success and error cases in the respective callbacks.
Creating the Custom Function in functions.php
Now, let's create the custom function in the functions.php
file that will handle the AJAX request and process the image uploads:
function your_custom_function(){
// initial response is false by default
$response = array ('status'=>false,'msg'=>'invalid code');
// you can have server side validation here if you want
// i.e. if(!$_REQUEST['fname']) this means if this field is not sent.. then return relevant response
if (!function_exists('wp_handle_upload')) {
require_once(ABSPATH . 'wp-admin/includes/file.php');
}
$yourDBTable = $wpdb->prefix.'yourDBTable';
$uploadedfile = $_FILES['identity'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
//after uploading to uploads DIR you will get url of your image here
$id_url = $movefile['url'];
$uploadedfile = $_FILES['residence'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
$resid_url = $movefile['url'];
$uploadedfile = $_FILES['selfie'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
$selfie_url = $movefile['url'];
$user_data = array(
'fname' => $_REQUEST['fname'],
'photo_identity' => $id_url,
'photo_selfie' => $selfie_url,
'photo_residence' => $resid_url
);
try {
$result = $wpdb->insert($yourDBTable,$user_data);
$response['status']=true;
} catch (Exception $e) {
$response['msg']="Something went wrong";
}
echo json_encode($response);
wp_die();
}
Let's break down the function:
- We start by initializing a
$response
array with a default status
of false
and a msg
of 'invalid code'
.
- We check if the
wp_handle_upload
function exists, and if not, we include the necessary file.
- We then get the values of the uploaded files from the
$_FILES
superglobal, and use the wp_handle_upload
function to move the files to the WordPress uploads directory. We store the URLs of the uploaded files in the $id_url
, $resid_url
, and $selfie_url
variables.
- We create an array
$user_data
that contains the first name and the three image URLs.
- We then try to insert the
$user_data
array into the $yourDBTable
table using the $wpdb->insert()
function. If the insert is successful, we set the $response['status']
to true
.
- If an exception is caught during the insert operation, we set the
$response['msg']
to "Something went wrong"
.
- Finally, we encode the
$response
array as JSON and use the wp_die()
function to exit the script.
This function handles the file uploads, stores the image URLs in the database, and returns a JSON response indicating the success or failure of the operation.
Integrating the AJAX Call and the Custom Function
To integrate the AJAX call and the custom function, you'll need to add the following code to your WordPress theme's functions.php file:
// Add the AJAX action to the WordPress action hooks
add_action('wp_ajax_your_custom_function', 'your_custom_function');
add_action('wp_ajax_nopriv_your_custom_function', 'your_custom_function');
This code adds the your_custom_function
action to the wp_ajax_your_custom_function
and wp_ajax_nopriv_your_custom_function
hooks, which will allow the AJAX call to trigger the custom function.
Now, in your custom page template, you can add the necessary HTML form fields and the jQuery code to make the AJAX call:
<form id="your-form">
<input type="text" id="fname" name="fname" placeholder="First Name" />
<input type="file" id="identity" name="identity" />
<input type="file" id="residenceID" name="residence" />
<input type="file" id="selfie" name="selfie" />
<button type="button" id="YourButtnID">Submit</button>
</form>
<script>
jQuery(document).ready(function($) {
$("#YourButtnID").click(function(){
var firstname = $('#fname').val();
var identity = jQuery('#identity').prop('files')[0];
var residence = jQuery('#residenceID').prop('files')[0];
var selfie = jQuery('#selfie').prop('files')[0];
var formData = new FormData();
formData.append('action','your_custom_function');
formData.append('fname',firstname);
formData.append('identity', identity);
formData.append('residence', residence);
formData.append('selfie', selfie);
$.ajax({
type: "POST",
url: ajaxurl,
contentType: false,
processData: false,
data: formData,
dataType: "JSON",
success:function(data){
if(data['status']){
//All went well
}else{
// something went wrong
}
},
error:function(err){
// You might not have caught any exception
}
});
});
});
</script>
In this example, we've added the form fields for the user's first name, identity, residence, and selfie images. We've also added the jQuery code to make the AJAX call when the "Submit" button is clicked.
By combining the AJAX call and the custom function in the functions.php
file, you can now handle image uploads in a custom WordPress page using AJAX. This approach can be particularly useful for building applications that require users to submit documents or proof of identity.
Remember to replace 'your_custom_function'
with the actual name of the function you created in the functions.php
file, and 'yourDBTable'
with the name of your database table.
Flowpoint.ai can help you identify all the technical errors that are impacting conversion rates on your website and directly generate recommendations to fix them.
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.