Auto Featured Image for Gravity Forms Posts by Response

This scenario is fairly specific, Gravity Forms to post and adding a specific featured image based on a form field but the ease of assigning a featured image via the media post ID is hand elsewhere and it’s always nice to document more ways to tweak Gravity Forms.

Step One

Upload your images to the WP Media Library. After uploading the images you want to use, go to the Media Library and change the view to list view. If you mouse over the edit button, you’ll see a URL appear in the bottom right of your browser window.
Shows clicking on list view in WordPress media file.

Setup Your Form

Take note of the entry ID of the form element that’s going to determine the featured image. It’s likely the same number you’d get if you counted the fields from top to bottom but if you made them and rearranged them it could be something else. If you mouse over the field in the form editor, you’ll see the form ID in blue.
Screenshot of gravity forms form ID on mouseover.

The Code

Now we’re just writing a bit of PHP to tie into the form. In this case I’m tying it just to form 5 with this action add_action( ‘gform_after_submission_5’, ‘altlab_timeline_featured_image’, 10, 2 );. Leaving off the _5 would apply it to all forms and changing the 5 to another number would target another form.

In this example I’m using field 3/question 3 to determine my featured image. It’s just a series of if statements to set our $img_id and then a final set_post_thumbnail to attach the image to the right post.

function altlab_timeline_featured_image($entry, $form){
	$timeline_type = rgar($entry, '3');
	if ($timeline_type  == 'First computer I owned' ){
		$img_id = 6895;
	}
	if ($timeline_type  == 'First time online'){
		$img_id = 6899;
	}
	if ($timeline_type  == 'First email'){
		$img_id = 6900;
	}
	if ($timeline_type  == 'First cell phone'){
		$img_id =  6898;
	}

	set_post_thumbnail( $entry['post_id'], $img_id );
}
add_action( 'gform_after_submission_5', 'altlab_timeline_featured_image', 10, 2 );

Comments on this post

No comments.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Trackbacks and Pingbacks on this post

No trackbacks.

TrackBack URL