Advertisement
Guest User

Untitled

a guest
Dec 5th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. add_action( 'gform_after_create_post', 'gf_add_to_media_library', 10, 3 );
  2.  
  3. /**
  4. * Save file upload fields under custom post field to the library
  5. *
  6. * @param int $post_id The post identifier
  7. * @param array $entry The entry
  8. * @param array $form The form
  9. */
  10. function gf_add_to_media_library ( $post_id, $entry, $form ) {
  11. foreach($form['fields'] as $field){
  12.  
  13. //get media upload dir
  14. $uploads = wp_upload_dir();
  15. $uploads_dir = $uploads['path'];
  16. $uploads_url = $uploads['url'];
  17.  
  18. //if its a custom field with input type file upload.
  19. if( $field['type'] == 'post_custom_field' && $field['inputType'] == 'fileupload'){
  20. $entry_id = $field['id'];
  21. $files = rgar ( $entry, $entry_id );
  22. $custom_field = $field['postCustomFieldName']; //custom field key
  23.  
  24. //if file field is not empty
  25. if ( $files !== ''){
  26. $patterns = ['[', ']', '"']; //get rid of crap
  27. $file_entry = str_replace($patterns, '', $files);
  28. $files = explode ( ',', $file_entry );
  29.  
  30. foreach ($files as $file) {
  31. //each file is a url
  32. //get the filename from end of url in match[1]
  33. $filename = pathinfo($file, PATHINFO_FILENAME);
  34. //add to media library
  35. //WordPress API for image uploads.
  36. include_once( ABSPATH . 'wp-admin/includes/image.php' );
  37. include_once( ABSPATH . 'wp-admin/includes/file.php' );
  38. include_once( ABSPATH . 'wp-admin/includes/media.php' );
  39.  
  40. $new_url = stripslashes($file);
  41. $result = media_sideload_image( $new_url, $post_id, $filename, 'src');
  42. //saving the image to field or thumbnail
  43. if( strpos($field['cssClass'], 'thumb') == false ){
  44. $attachment_ids[] = (int) get_attachment_id_from_src($result);
  45. }
  46. else{
  47. set_post_thumbnail($post_id, (int) get_attachment_id_from_src($result) );
  48. }
  49.  
  50. } //end foreach file
  51.  
  52. update_post_meta ($post_id, $custom_field, $attachment_ids);
  53. } //end if files not empty
  54. } //end if custom field of uploadfile
  55. }
  56. } //end for each form field
  57.  
  58.  
  59. function get_attachment_id_from_src($image_src) {
  60.  
  61. global $wpdb;
  62. $query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'";
  63. $id = $wpdb->get_var($query);
  64. return $id;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement