Skip to content

Instantly share code, notes, and snippets.

@joshuadavidnelson
Last active April 5, 2017 03:36
Show Gist options
  • Save joshuadavidnelson/35da6eb43022399287fc to your computer and use it in GitHub Desktop.
Save joshuadavidnelson/35da6eb43022399287fc to your computer and use it in GitHub Desktop.
Connect a Gravity Form upload field to ACF Gallery Field when creating a front-end post submission, requires the jdn_create_image_id function from https://gist.github.com/joshuadavidnelson/164a0a0744f0693d5746
<?php
/**
* Attach images uploaded through Gravity Form to ACF Gallery Field
*
* @author Joshua David Nelson, [email protected]
* @return void
*/
$gravity_form_id = 1; // gravity form id, or replace {$gravity_form_id} below with this number
add_filter( "gform_after_submission_{$gravity_form_id}", 'jdn_set_post_acf_gallery_field', 10, 2 );
function jdn_set_post_acf_gallery_field( $entry, $form ) {
$gf_images_field_id = 1; // the upload field id
$acf_field_id = 'field_546d0ad42e7f0'; // the acf gallery field id
// get post, if there isn't one, bail
if( isset( $entry['post_id'] ) ) {
$post = get_post( $entry['post_id'] );
if( is_null( $post ) )
return;
} else {
return;
}
// Clean up images upload and create array for gallery field
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 ) {
// NOTE: this is the other function you need: https://gist.github.com/joshuadavidnelson/164a0a0744f0693d5746
if( ! class_exists( 'JDN_Create_Media_File' ) )
break;
// Create the media library attachment and store the attachment id in the gallery array
$create_image = new JDN_Create_Media_File( $value, $post->ID );
$image_id = $create_image->attachment_id;
if( absint( $image_id ) ) {
$gallery[] = $image_id;
}
}
}
}
// Update gallery field with array
if( ! empty( $gallery ) ) {
update_field( $acf_field_id, $gallery, $post->ID );
}
}
@vagu71
Copy link

vagu71 commented Nov 18, 2015

Hi Joshua,

Awesome code, thanks for sharing it.

Quick question though.....is there a way to delete the file thats uploaded as the acf image field? So basically, ACF is storing the id of the image(s).

2 problems are coming up:

  1. If the admin deletes the image from the backend, they dont show up in the edit screen on the backend. However on the frontend, the form loads up with the old field value in the ginput_preview.
  2. Is there a way to delete the actual file from the media library so that the filesystem does not run into gigs. And also is there a way to stop GF loading up with the preview value even though the value's been deleted by the admin from the backend?

Thanks Joshua!

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