Skip to content

Instantly share code, notes, and snippets.

@lmeyer
Last active October 14, 2016 15:21
Show Gist options
  • Save lmeyer/67d61d8d0d3b034f3f25f26176e9570b to your computer and use it in GitHub Desktop.
Save lmeyer/67d61d8d0d3b034f3f25f26176e9570b to your computer and use it in GitHub Desktop.
Connect Gravity Forms upload field to a Metabox image field
<?php
$gravity_form_id = 1; // gravity form id, or replace {$gravity_form_id} below with this number
add_filter( "gform_after_submission_{$gravity_form_id}", 'hdco_set_post_metabox_field', 10, 2 );
function hdco_set_post_metabox_field( $entry, $form ) {
$gf_images_field_id = 18; // the upload field id
$metabox_field_id = 'images_gallery'; // the metabox field id
if( isset( $entry['post_id'] ) ) {
$post = get_post( $entry['post_id'] );
if( is_null( $post ) )
return;
} else {
return;
}
if( isset( $entry[ $gf_images_field_id ] ) ) {
$images = stripslashes( $entry[ $gf_images_field_id ] );
$images = json_decode( $images, true );
if( !empty( $images ) && is_array( $images ) ) {
$gallery = array();
foreach( $images as $key => $value ) {
if( function_exists( 'hdco_sideload_image' ) ) {
// Download the file in media library and get the Id
$image_id = hdco_sideload_image( $value, $post->ID );
}
if( $image_id ) {
$gallery[] = $image_id;
}
}
}
}
if( ! empty( $gallery ) ) {
foreach($gallery as $image_id) {
add_post_meta($post->ID, $metabox_field_id, $image_id);
}
wp_update_post( $post );
}
}
<?php
function hdco_sideload_image( $image_url, $parent_post_id = null ) {
if ( !function_exists('media_handle_upload') ) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if( empty( $image_url ) || ! esc_url( $image_url ) )
return false;
$image_url = esc_url( $image_url );
$tmp = download_url( $image_url );
if( is_wp_error( $tmp ) ){
// download failed, handle error
}
$file_array = array();
// File base name, e.g. image.jpg
$file_base_name = basename( $image_url );
$filetype = wp_check_filetype( $file_base_name, null );
if( !empty( $filetype ) && is_array( $filetype ) ) {
// Create attachment title - basically, pull out the text
$post_title = preg_replace( '/\.[^.]+$/', '', $file_base_name );
$file_array['name'] = $file_base_name;
$file_array['tmp_name'] = $tmp;
// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
@unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
}
// do the validation and storage stuff
$id = media_handle_sideload( $file_array, $parent_post_id);
// If error storing permanently, unlink
if ( is_wp_error($id) ) {
@unlink($file_array['tmp_name']);
return false;
}
return $id;
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment