Last active
January 30, 2020 21:51
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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 ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!