Skip to content

Instantly share code, notes, and snippets.

@Sidsector9
Last active January 30, 2020 21:51
Show Gist options
  • Select an option

  • Save Sidsector9/65016f2d4a8f001a123bd50b275bc964 to your computer and use it in GitHub Desktop.

Select an option

Save Sidsector9/65016f2d4a8f001a123bd50b275bc964 to your computer and use it in GitHub Desktop.
Gravity forms set featured image using Standard and Advanced fields through URL to attachment conversion
<?php
add_action( 'gform_after_submission', 'upload_photo', 10, 2 );
function convert_to_attachment( $entry, $form ) {
// ID of the title field
$title = rgar( $entry, 1 );
// ID of the upload button
$url = rgar( $entry, 2 );
$args = array(
'post_title' => $title,
'post_type' => 'photo' // Custom Post Type
);
$post_id = wp_insert_post( $args );
// Current directory
$abs_path = getcwd();
// Convert to absolute URL
$url = str_replace( site_url(), $abs_path, $url);
// Checking filetype for MIME
$filetype = wp_check_filetype( basename( $url ), null );
// WordPress upload directory
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $url ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $url ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Get attachment ID
$attach_id = wp_insert_attachment( $attachment, $url, $post_id );
// Dependency for wp_generate_attachment_metadata().
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate metadata for image attachment.
$attach_data = wp_generate_attachment_metadata( $attach_id, $url );
wp_update_attachment_metadata( $attach_id, $attach_data );
// Set as featured image for the post created on line 13.
set_post_thumbnail( $post_id, $attach_id );
}
@Garth619
Copy link
Copy Markdown

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment