Skip to content

Instantly share code, notes, and snippets.

@endurtech
Last active November 16, 2022 13:43
Show Gist options
  • Save endurtech/11c1ffee4c597e7f711412cf760eedb2 to your computer and use it in GitHub Desktop.
Save endurtech/11c1ffee4c597e7f711412cf760eedb2 to your computer and use it in GitHub Desktop.
The following code, when inserted into a custom plugin or your child theme’s functions.php file will forward all file uploads (images and documents) to your Media Library within your WordPress website. As originally seen on: https://infinitesynergysolutions.com/learning-center/add-gravity-forms-file-uploads-and-image-uploads-to-the-media-library/
<?php
// Uploading to the Media Library Using Gravity Forms
// https://endurtech.com/upload-to-the-media-library-using-gravity-forms/
add_action( 'gform_after_submission', 'iss_gf_after_submission', 10, 2 );
function iss_gf_after_submission( $entry, $form )
{
// Walk through form fields, find file upload fields
foreach( $form['fields'] as $field )
{
if( $field->type == 'fileupload' )
{
// See if file was submitted with entry
if( isset( $entry[$field->id] ) )
{
$fileurl = $entry[$field->id];
// ID of post this attachment is for. 0 for unattached
$parent_post_id = 0;
// Check type of file, for use as 'post_mime_type'
$filetype = wp_check_filetype( basename( $fileurl ), null );
// Path to upload directory
$wp_upload_dir = wp_upload_dir();
// Gravity Forms uses its own upload folder, get that location
$parts = explode( 'uploads/', $entry[$field->id] );
$filepath = $wp_upload_dir['basedir'].'/'.$parts[1];
$fileurl = $wp_upload_dir['baseurl'].'/'.$parts[1];
// Array of post data for attachment
$attachment = array(
'guid' => $fileurl,
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $fileurl ) ),
'post_content' => '',
'post_status' => 'inherit');
// Insert attachment
$attach_id = wp_insert_attachment( $attachment, $filepath, $parent_post_id );
// Image manipulations are an admin side function. Gravity Forms is a frontend function, include image manipulations here.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate metadata for attachment, update database
if( $attach_data = wp_generate_attachment_metadata( $attach_id, $filepath ) )
{
wp_update_attachment_metadata( $attach_id, $attach_data );
} else {
echo '<div id="message" class="error"><h1>Failed to create Meta-Data</h1></div>';
}
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment