Search

5-Step Guide to Add File Upload in EE4 Registration Form

Listen to this article

It’s simple. This is what I wanted to achieve:

file-upload-registration-form-ee4

On a recent project, I had to add a file upload option in the events registration form. The client was using Event Espresso 4. Instinctively I searched for a file upload add-on. I was pessimistic though. At the back of my mind I knew there was no such add-on. I browsed through the support forums as well. And here’s what I found:

ee4-file-upload

Okay. So, the solution was to build the file upload functionality into Event Espresso (EE4) myself. I discuss this with the client and went ahead with the development. I’m assuming quite a few of you would be interested in a similar solution, so I’ve listed the steps below. Feel free to tweak it according to your requirements.

Note: If you haven’t done this before and have no clue about PHP, JS or WordPress coding, you better contact an Event Espresso Pro developer. (We’re on that list, just so you know :D)

[space]

Step #1 Create an Add-On Plugin

Let’s name our add-on ‘WDM File Upload’ for Event Espresso 4 (EE4). We have to create a folder of the same name ‘wdm-file-upload-ee4’, and we’ll create a PHP file ‘wdm-file-upload-ee4.php’ under it, which will be our main plugin file.

In ‘wdm-file-upload-ee4.php’ add the below headers:

<?php

/*
Plugin Name: WDM File Upload
Description: Adds a file upload functionality in Event Espresso 4 registration form.
Version:     1.0.0
Author:      your-name
*/

/*
* Since we are creating an add-on for EE4 we have to check if Event Espresso is active.
**/
if ( in_array( 'ee4-folder-name/espresso.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    /* Plugin code will go here */
}

Replace ee4-folder-name with the Event Espresso 4 plugin folder name.

[space]

Step #2 Add a File Upload field in Event Registration Form

We have to then add an upload file field in the registration form. For this we’ll be using the ‘AHEE__before_spco_whats_next_buttons’ hook. This hook is called when the registration form is being filled. Let’s assume we want event attendees to upload an image. We can use the below code:

add_action('AHEE__before_spco_whats_next_buttons','wdm_display_upload_option',10,2);
function wdm_display_upload_option( $current_step, $next_step )
{
    if('attendee_information'==$current_step )
    {
?>
    <label for="fileToUpload">Upload Your File</label>
    <input type="file" accept="image/*" name="fileToUpload" id="fileToUpload">

<?php
    }
}

[space]

Step #3 Add the supporting JS Code

We’ll be handling the file upload via AJAX, for which we need some JS code. To add the JS code, we need to create a ‘js’ folder under our main plugin folder. In this ‘wdm-file-upload-ee4/js’ folder, we need to add a ‘wdm-file-upload-ee4.js’ file, where we’ll be adding our supporting JS code.

In the JS file we need to add the below code:

jQuery(document).ready(function()
{
    jQuery("#fileToUpload").change(function(){
        formdata = new FormData();
        var file;        
        var len= this.files.length;
        if ( len > 0 )
        {
                file = this.files[0];                
                if ( formdata ) 
                {
                        formdata.append( "fileToUpload", file );
                        formdata.append('action','wdm_upload_image_action');
                        formdata.append('_wdmnonce', wdm_ee_object.ajax_nonce);
                }
            
        }
        else
        {
            formdata = false;
        }
        
        if ( formdata ) 
        {            
            jQuery.ajax({    
                            type: 'POST',
                            url: wdm_ee_object.ajax_url,
                            data: formdata,
                            processData: false,
                            contentType: false,
                            success: function ( response )
                            {
                                /*handle response */  
                                jQuery("#fileToUpload").val('');
                            }
                        });
        }
   });
});

We have to then enqueue the JS file so that it is picked up by WordPress. For this, add the below code in ‘wdm-file-upload-ee4.php’

// enqueue the script when the registration form is displayed
add_action( 'AHEE__SPCO__before_registration_steps', 'wdm_file_upload_enqueue_scripts'); function wdm_file_upload_enqueue_scripts() {
    wp_enqueue_script('wdm-upload-script', plugin_dir_url( __FILE__ ) . '/js/wdm-file-upload-ee4.js',array('jquery'));
    $wdm_localize_array = array(
                   'ajax_nonce' => wp_create_nonce( 'wdm-ee4-upload' ),
                   'ajax_url'   => admin_url( 'admin-ajax.php' ),
                 );
    wp_localize_script( 'wdm-upload-script', 'wdm_ee_object', $wdm_localize_array );
}

[space]

Step #4 Add the PHP Code to Upload the file

We have to handle the AJAX request in our  ‘wdm-file-upload-ee4.php’ file. For this you can use the below code:

add_action( 'wp_ajax_wdm_upload_image_action', 'wdm_upload_image_action_callback' );
add_action( 'wp_ajax_nopriv_wdm_upload_image_action', 'wdm_upload_image_action_callback' );
function wdm_upload_image_action_callback(){
  check_ajax_referrer( 'wdm-ee4-upload', '_wdmnonce' );
  if(!empty($_FILES))
  {
    //Check if there are any errors in the upload.
    if($_FILES['fileToUpload']['error'] > 0){
      die('An error occurred when uploading.');
    }

    /* validate the file type */

    // check if a file with the same name exists
    if(file_exists('upload/' . $_FILES['fileToUpload']['name'])){
      die('File name exists.');
    }

    //get file path
    $filename=$_FILES['fileToUpload']['name'];
    $type=$_FILES['fileToUpload']['type'];
    $tmp_name=$_FILES['fileToUpload']['tmp_name'] ;
    $error=$_FILES['fileToUpload']['error'];
    $size=$_FILES['fileToUpload']['size'];
    
    //Upload Files to WordPress Uploads Folder
    if ( ! function_exists( 'wp_handle_upload' ) )
      require_once( ABSPATH . 'wp-admin/includes/file.php' );

    $uploadedfile = $_FILES[$fileToUpload];
    $upload_overrides = array('test_form' => false, 
                              'test_size' => true,
                              'test_upload' => true,
                              );

    $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );

    if ( $movefile )
    {
      //file is uploaded successfully
    }
    else
    {
      // upload error :-(
     }
  }
}

[space]

Step #5 Install and Activate your Plugin

So, the final step is to zip up our add-on plugin folder and to upload and activate it. You should then see a file upload option for your registration forms!

And there you have it. You’ve just added a file upload functionality in Event Espresso 4. If you have any doubts or questions do send them to me using the comment section below! 🙂

Aparna Gawade

Aparna Gawade

6 Responses

    1. Hi Xander,
      The code provided is for EE4. EE3 and EE4 are coded differently, so yes, it won’t work with EE3.

  1. In what you’ve posted above, is the file just added to the media library, or is it connected to the user or registration in some way?

    This is so great – thanks for sharing this!

    1. Hi David,

      The above code just uploads the image to the media library, but you can use the below code to link it to the user (add this code on successful file upload):

                      //file is uploaded successfully. now insert record in table wp_posts and wp_postmeta
                      $wp_filetype = $movefile['type'];
                      $filename = $movefile['file'];
      
                      // Get the path to the upload directory.
                      $wp_upload_dir = wp_upload_dir();
                     
                      $attachment = array(
                                          'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
                                          'post_mime_type' => $wp_filetype,
                                          'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
                                          'post_content' => '',
                                          'post_status' => 'inherit'
                                      );
                      // Insert the attachment.
                      $attach_id = wp_insert_attachment( $attachment, $filename,$att_id);
      
                      // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
                      require_once( ABSPATH . 'wp-admin/includes/image.php' );
                       $p=$wp_upload_dir['subdir']. '/' .$filename; 
      
                      // Generate the metadata for the attachment, and update the database record.
                       // Define attachment metadata
                     $attach_data = wp_generate_attachment_metadata( $attach_id, $p );
                     
                     // Assign metadata to attachment
                     wp_update_attachment_metadata( $attach_id, $attach_data ); 
                     
                     //to assign metavalue for image_upload
                     update_post_meta($attach_id, 'wdm_custom_image_upload', 'yes'); 
                     
                      //set feature image for the post
                     set_post_thumbnail( $att_id, $attach_id );
                     
                   //echo image url
                     echo $attachment['guid'];
      
  2. Hi!

    I tryied your code and dont get it to work.. when i upload the picture it’s disipears …

    Do you have the full code how it looks like in the plugin and js file?

    Best regards!

    1. I have been trying to get the file upload to work with newest version of EE4 and i cannot get this plugin or the one that event Espresso advertises to do file uploads. Nothing seems to happen when choosing a file. I just get taken through to the success page but no file gets uploaded to the uploads directory.

      Is there something in WordPress 4.8 that breaks this function?

Leave a Reply

Your email address will not be published. Required fields are marked *

Get The Latest Updates

Subscribe to our Newsletter

A key to unlock the world of open-source. We promise not to spam your inbox.

Suggested Reads

WordPress Development

Custom WordPress Solutions, for You

LearnDash Development

Custom LearnDash Solutions, for You

WooCommerce Development

Custom WooCommerce Solutions, for You

WordPress Plugins

Scale your WordPress Business

WooCommerce Plugins

Scale your WooCommerce Business

LearnDash Plugins

Scale your LearnDash Business

Label

Title

Subtext

Label

Title

Subtext

Join our 55,000+ Subscribers

    The Wisdm Digest delivers all the latest news, and resources from the world of open-source businesses to your inbox.

    Suggested Reads

    WordPress Tips & Tricks
    Ketan Vyawahare

    How to Make Responsive Tables using CSS without Tag Read More »