<?php

add_action( 'gform_advancedpostcreation_post_after_creation', function ( $post_id, $feed, $entry, $form ) {

  // the posts that are attachments of the new post
  $attachments = get_posts( array(
    'post_type'      => 'attachment',
    'posts_per_page' => -1,
    'post_parent'    => $post_id,
    'exclude'        => get_post_thumbnail_id()
  ) );

  // the meta values for media fields, should be an attachment post id or an array of attachment post ids
  $post_meta_media = array();


  // loop through all of the form field ids that were used to attach media
  foreach ($feed['meta']['postMedia'] as $field_id) {

    // check if a single file was added or a list of files were added
    if ( preg_match( '/^\[.+\]$/', $entry[$field_id] ) ) {
      $gf_file_urls = json_decode( $entry[$field_id], true );
      $is_gallery = true;
    } else {
      $gf_file_urls = array( $entry[$field_id] );
      $is_gallery = false;
    }


    // use each gf upload to find the post attachment id for the field
    $wp_attachment_ids = array();
    
    foreach ($gf_file_urls as $gf_file_url) {

      $matches = array();
      preg_match(
        '/\/([^\/]+)\.(\w+)$/',
        $gf_file_url,
        $matches
      );

      $gf_file_title = $matches[1];
      $gf_file_ext = $matches[2];

      foreach ( $attachments as $attachment ) {
        $matches = array();
        preg_match(
          '/\.(\w+)$/',
          $gf_file_url,
          $matches
        );
        $attachment_ext = $matches[1];
        if ( $attachment->post_title == $gf_file_title && $attachment_ext === $gf_file_ext ) {
          if ($is_gallery) {
            $wp_attachment_ids[] = $attachment->ID;
          } else {
            $wp_attachment_ids = $attachment->ID;
          }
          break;
        }
      }
    }

    $post_meta_media[ $field_id ] = $wp_attachment_ids;
  }

  // replace the meta fields with the post attachments
  foreach ($feed['meta']['postMetaFields'] as $meta_field) {
    if ( isset( $post_meta_media[ $meta_field[ 'value' ] ] ) ) {
      update_field( $meta_field[ 'custom_key' ], $post_meta_media[ $meta_field[ 'value' ] ], $post_id );
    }
  }

}, 10, 4 );
