Skip to content

Instantly share code, notes, and snippets.

@joshuadavidnelson
Last active October 11, 2018 19:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuadavidnelson/acfed1e71a9c69166e77a0c7799af6b6 to your computer and use it in GitHub Desktop.
Save joshuadavidnelson/acfed1e71a9c69166e77a0c7799af6b6 to your computer and use it in GitHub Desktop.
<?php
/**
* Associate an uploaded file with a post on form submission in Gravity Forms
*
* This is specific to a comment on my post about connecting GF with ACF
*
* @see https://joshuadnelson.com/connect-gravity-forms-file-upload-to-acf-gallery-field/#comment-13186
* @author Joshua David Nelson, josh@joshuadnelson.com
*/
$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_add_file_to_post', 10, 2 );
function jdn_add_file_to_post( $entry, $form ) {
// Assumes you're creating a post on form submissions, needs the post id from the form submission
// If you're not doing this, remove this check and replace the $post->ID below with the post's id
// (or remove it to not associate the media file with a post)_
if( isset( $entry['post_id'] ) ) {
$post = get_post( $entry['post_id'] );
if( is_null( $post ) )
return;
} else {
return;
}
$gf_upload_field_id = 7; // the upload field id
// Make sure we have a value for the field id
if( isset( $entry[ $gf_upload_field_id ] ) ) {
$file_url = esc_url( $entry[ $gf_upload_field_id ] );
if( $file_url ) {
$media_file = new JDN_Create_Media_File( $file_url, $post->ID ); // needs a post id to attach it to a post
update_post_meta( $post->ID, 'featured_pdf', $media_file->attachment_id ); // add the pdf to the post via a custom meta
}
}
}
// Access the pdf elsewhere
$pdf_id = get_post_meta( $post_id, 'featured_pdf', true);
$pdf_url = wp_get_attachment_url( $pdf_id );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment