@Alex Cancado:
I'm using your function above (the one with multiple file upload fields) to rename the uploaded files – works like a charm. The files get renamed and the DB fields are updated.
I now made a function that takes the custom field values of the file upload fields and adds them as attachments so that I can see them in the media library. It looks like that:
add_action("gform_post_submission", "usr_custom_fields_to_attachment", 10, 2);
function usr_custom_fields_to_attachment($entry, $form){
//ignore requests from forms other than ID 1
if($form['id'] != 1)
return;
//getting post
$post = get_post($entry['post_id']);
// add uploaded files as post attachment
$file_values = get_post_custom_values('file_upload', $post->ID);
foreach($file_values as $value) {
if($value != ''){
//update post meta with absolute path (needed for wp_insert_attachment)
$abspath = $_SERVER['DOCUMENT_ROOT'] . wp_make_link_relative($value);
update_post_meta($post->ID, 'file_upload', $abspath, $value);
//check file type
$wp_filetype = wp_check_filetype(basename($abspath), null );
//create attachment object
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($abspath)),
'post_content' => '',
'post_status' => 'inherit'
);
//insert attachment and process attached file
$attach_id = wp_insert_attachment($attachment, $abspath, $post->ID);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $abspath);
wp_update_attachment_metadata($attach_id, $attach_data);
}
}
}
My problem now is: When I use your function, the custom fields won't get updated (only the DB), so in there is still the link with the old file name. My function then processes the outdated custom fields and of course can't find the image. I'm unable to see how I can update the metadata inside your function or to get the updated fields directly out of the DB and use them inside my function. Any help?
I set up the fields in your function like that (The last added parameter in usr_rename_file is only used for the new filename):
add_action("gform_post_submission", "usr_rename_fileuploads", 10, 2);
function usr_rename_fileuploads($entry, $form){
//ignore requests from forms other than ID 1
if($form["id"] != 1)
return;
usr_rename_file($entry, $form, 28, 1); //renaming file upload field 1 id=28
usr_rename_file($entry, $form, 29, 2); //renaming file upload field 2 id=29
usr_rename_file($entry, $form, 30, 3); //renaming file upload field 3 id=30
}
Another little question on top: If the user doesn't upload a second or third file, Gravity Form anyway creates the custom field but without value. How can I avoid this behavior?
Thanks!
Posted 13 years ago on Saturday August 27, 2011 |
Permalink