Skip to main content

Gravity Forms – Assign a file upload to an Advanced Custom Fields file field : WordPress Code Snippet

The following makes use of the Gravity Forms Advanced Post Creation Addon and handles adding a file from a specific Gravity Forms file field to the an Advanced Custom Fields post created by the plugin.

You could also look to use a hook such as gform_after_submission in place of this with some tweaking.

/**
 * Gravity Forms - handle file field upload and assign to ACF file field
 */

add_action( 'gform_advancedpostcreation_post_after_creation_2', function( $post_id, $feed, $entry, $form ) {
    $file_field_entry_key = 5;

    if ( $image_url = rgar( $entry, $file_field_entry_key ) ) {
        $image_path = $_SERVER['DOCUMENT_ROOT'] . wp_make_link_relative( $image_url );

        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        require_once( ABSPATH . 'wp-admin/includes/file.php' );
        require_once( ABSPATH . 'wp-admin/includes/media.php' );

        $filetype = wp_check_filetype( basename( $image_path ), null );

        $file_array = [
            'name'     => basename( $image_path ),
            'type'     => $filetype,
            'tmp_name' => $image_path,
            'error'    => 0,
            'size'     => filesize( $image_path ),
        ];

        $attachment_id = media_handle_sideload( $file_array, $post_id );

        update_field( 'YOUR_FIELD_NAME', $attachment_id, $post_id );
    }
}, 10, 4 );

Remember to change the value ‘2’ in the action name to the ID of your Gravity Form and the entry key value for $file_field_entry_key to the key of your field. The key number can be found in the $entry variable.

‘YOUR_FIELD_NAME’ will need to be changed to your Advanced Custom Fields field name.