Skip to content

Instantly share code, notes, and snippets.

@rosswintle
Created September 20, 2013 10:52
Show Gist options
  • Save rosswintle/6635876 to your computer and use it in GitHub Desktop.
Save rosswintle/6635876 to your computer and use it in GitHub Desktop.
Code to convert Gravity Forms file uploads to media items and attach to a post.
/*
* There are a couple of places where we use GravityForms to do a file upload into a
* meta-data item of type "upload". The upload file type stores an attachment ID,
* whereas the Gravity Forms upload field stores a URL.
*
* This function is used to convert a URL in the meta-data item specified by the
* $field parameter to an attachment ID - creating the attachment as it goes.
*
* This function should be called from a callback hooked to gform_after_submission_[x]
*
* This is based on the code here: http://www.pastie.org/3167687
* which was submitted to this support thread: http://www.gravityhelp.com/forums/topic/file-upload-as-attachment-id
*/
function convert_upload_field_url_to_attachment( $post_id, $field) {
$success = false;
$filename = get_post_meta($post_id, $field, true);
if(!is_numeric($filename) && $filename != '') {
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
//Get the absolute path of the uploaded image by Gravity Forms
$abs_path = getcwd();
$actual_file = str_replace(site_url(),$abs_path,$filename);
$attach_id = wp_insert_attachment( $attachment, $actual_file, $post_id );
//Update Media Metadata
//require_once(ABSPATH . 'wp-admin/includes/image.php');
//$attach_data = wp_generate_attachment_metadata( $attach_id, $actual_file );
//wp_update_attachment_metadata( $attach_id, $attach_data );
if($attach_id) {
update_post_meta($post_id, $field, $attach_id);
$success = true;
}
}
return $success;
}
@morgyface
Copy link

This looks like exactly what I need, though I'm struggling to implement. Could I be so bold as to ask for your help?

@Sidsector9
Copy link

How to get the attachment id of an image that was uploaded using the 'Post Image' post field in gravity forms?
I'm trying to add a post from the front end using wp_insert_post, I need an attachment id to pass it to update_post_meta. Is this possible?

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