Gravity forms is a powerful form package and while its really good out of the box. Sometimes it needs a little something extra to get it singing in the right key. This is the first of a series of posts with some simple but (hopefully) helpful add on functions.
Even using the Gravity Forms +Custom Post Types, uploaded images are stored in a gravity forms folder, rather than the media library. Which for some uses is not a problem, but if you want to leverage multiple image sizes at the heart of WordPress, its a real pain.
By making use of the gform_after_submission hook, the file can be moved and added to the media library. This not only allows you to make use of different resolutions for themes, but also for easy use in posts later on. I use this simple solution on a number of sites which have either front end submissions
Now for the fun part, first the function takes the URL and downloads the file to a temporary folder.
- Takes the new temp URL (this can be used to transfer/upload files from external sources) and calls the wp_handle_sideload function (returning an array as $results). This uploads the image to regular media library, after checking the file type is allowed.
- Next we take the $results array and begin the process of adding the files to the media library (creating the various resized/cropped images) in the process. wp_insert_attachment is called to add the image to the library, $attach_id is returned here. You can return this array (by replacing $thumbnail with $attach_id on the return at the end).
- Now we update the database with the meta data, making use of wp_update_attachment_metadata.
- The image is now uploaded and added to the media library, we can now do as we wish. We have the attachmentID, so we can call out any version using wp_get_attachment_image_src. Really handy if you set numerous image sizes using add_image_size.
Hopefully this will help someone else out.