Skip to content

Instantly share code, notes, and snippets.

@saltnpixels
Last active January 18, 2024 20:32
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save saltnpixels/1056f39b97c1d19ee18f8e30fbdada6d to your computer and use it in GitHub Desktop.
gravity form upload file to media library and use attachment ID in custom field
add_action( 'gform_after_create_post', 'gf_add_to_media_library', 10, 3 );
/**
* Save file upload fields under custom post field to the library
*
* @param $post_id The post identifier
* @param $entry The entry
* @param $form The form
*/
function gf_add_to_media_library ( $post_id, $entry, $form ) {
foreach($form['fields'] as $field){
//get media upload dir
$uploads = wp_upload_dir();
$uploads_dir = $uploads['path'];
$uploads_url = $uploads['url'];
//if its a custom field with input type file upload.
if( $field['type'] == 'post_custom_field' && $field['inputType'] == 'fileupload'){
$entry_id = $field['id'];
$files = rgar ( $entry, $entry_id );
$custom_field = $field['postCustomFieldName']; //custom field key
//if file field is not empty or not []
if ( $files !== '' && $files !== "[]"){
$patterns = ['[', ']', '"']; //get rid of crap
$file_entry = str_replace($patterns, '', $files);
$files = explode ( ',', $file_entry );
foreach ($files as $file) {
//each file is a url
//get the filename from end of url in match[1]
$filename = pathinfo($file, PATHINFO_FILENAME);
//add to media library
//WordPress API for image uploads.
include_once( ABSPATH . 'wp-admin/includes/image.php' );
include_once( ABSPATH . 'wp-admin/includes/file.php' );
include_once( ABSPATH . 'wp-admin/includes/media.php' );
$new_url = stripslashes($file);
$result = media_sideload_image( $new_url, $post_id, $filename, 'src');
//saving the image to field or thumbnail
if( strpos($field['cssClass'], 'thumb') === false ){
$attachment_ids[] = (int) get_attachment_id_from_src($result);
}
else{
set_post_thumbnail($post_id, (int) get_attachment_id_from_src($result) );
}
} //end foreach file
if ( isset( $attachment_ids ) ){
update_post_meta ($post_id, $custom_field, $attachment_ids);
}
} //end if files not empty
} //end if custom field of uploadfile
}
} //end for each form field
function get_attachment_id_from_src($image_src) {
global $wpdb;
$query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'";
$id = $wpdb->get_var($query);
return $id;
}
@saltnpixels
Copy link
Author

saltnpixels commented Dec 5, 2016

In gravity forms there are two upload fields:
post image: this one has no size and dimension settings and is limited
fileupload: great but cannot upload to the media library

you can add fileupload as custom field but it just uses the src tot he gravity form upload and it wont add it to library.
This fixes that!

Just add a new gfield of custom field. set it to upload. You can even set it to multiple!
It will save an array of the images into the custom field and upload them to the media library.
Works great with Pods.
screenshot 2016-12-05 15 48 25

@saltnpixels
Copy link
Author

Now you can add the css class thumb onto the file upload you want to make into a thumbnail -featured image

@intothevoid0
Copy link

I'm using this snippet now, and for some reason, it's creating a draft post at the same time as it's uploading the image to the media library. Is there any way to avoid this from happening?

@craigiswayne
Copy link

@intothevoid0 As far as i know, Custom Fields are generally used for attaching to form field data to the post meta, which is why you're getting a draft post being created... to be honest, don't think there is a way around that unfortunately

@juaevpa
Copy link

juaevpa commented Dec 11, 2018

How it could be used in the user registration form? I'm not be able to make it work with users

@frank6tg
Copy link

Worked Beautifully! Thank you, thank you, thank you!

@theheartypixel
Copy link

Quick question... how do we assign the new image URL (from the media gallery) to the custom field. Currently, the upload works great, but the custom field is still pointing to the gravity forms upload directory and not the Media Gallery upload directory. See screenshot here: http://b3.ms/P5Z9ZD6gKnlb

Would like to update it to the URL of the uploaded photo after this function has placed it into the WP Media Gallery: http://idahoforests.local/wp-content/uploads/forest-photo-driggs5.jpg

@Aineia
Copy link

Aineia commented May 14, 2019

Hello! A noob question. Where do i put this php file in order for this to work :)?. Or just copy this into theme's functions.php?
Many thanks for your help.

@DCox44
Copy link

DCox44 commented Sep 5, 2019

Hi, I'm getting this error

Catchable fatal error: Object of class WP_Error could not be converted to string in C:\wamp64\www\Intranet\wp-content\themes\woffice\functions.php on line 152

Line 152 is the $query assignment

$query = "SELECT ID FROM '{$wpdb->posts}' WHERE guid='$image_src'";

any idea on why I'm getting this error?

@jadealombro
Copy link

Thank you @saltnpixels!

@technohack11
Copy link

I copied the code to my functions.php file and changed the "postCustomFieldName" to my custom field name "test_image_upload".
but it is not working. when I upload an image to the field, there is no image uploaded to the media library. Any one knows why?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment