Auto-attach Images from Child Form to Parent Post

This snippet assumes you have a parent form that is used to generate to a new post via the Advanced Post Creation add-on – and – a child form that contains a Post Image field. With this snippet in place, all images uploaded via the child form will be automatically attached to the post generated for the parent form. Posts generated by the child form will be deleted.

Code

Filename: gpnf-attach-child-form-post-images-to-parent-post.php

<?php
/**
 * Gravity Perks // Nested Forms // Auto-attach Images from Child Form to Parent Post
 * https://gravitywiz.com/documentation/gravity-forms-nested-forms/
 *
 * This snippet assumes you have a parent form that is used to generate to a new post via the Advanced Post Creation
 * add-on – and – a child form that contains a Post Image field. With this snippet in place, all images uploaded via
 * the child form will be automatically attached to the post generated for the parent form. Posts generated by the
 * child form will be deleted.
 */
// Update "123" to your parent form ID.
add_action( 'gform_advancedpostcreation_post_after_creation_123', function( $post_id, $feed, $entry, $form ) {

	$parent_entry  = new GPNF_Entry( $entry );
	$child_entries = $parent_entry->get_child_entries();

	foreach ( $child_entries as $child_entry ) {

		if ( ! $child_entry['post_id'] ) {
			return;
		}

		$attachments = get_posts( array(
			'post_type'      => 'attachment',
			'posts_per_page' => -1,
			'post_parent'    => $child_entry['post_id'],
		) );

		foreach ( $attachments as $attachment ) {
			wp_update_post( array(
				'ID'          => $attachment->ID,
				'post_parent' => $post_id,
			) );
		}

		wp_delete_post( $child_entry['post_id'] );

	}

}, 10, 5 );

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Trouble installing this snippet? See our troubleshooting tips.
  • Need to include code? Create a gist and link to it in your comment.
  • Reporting a bug? Provide a URL where this issue can be recreated.

By commenting, I understand that I may receive emails related to Gravity Wiz and can unsubscribe at any time.