Rename Uploaded Files For Gravity Forms
Rename uploaded files for Gravity Forms. You can create a static naming template or using merge tags to base names on user input.
March 23, 2022: Fixed issue where editing entries belonging to forms with multiple GW_Rename_Uploaded_Files
on the same form would cause files to be re-renamed.
March 12, 2021: Added ignore_extension
option.
June 12, 2020: Improved support for non-latin characters.
Jun 27, 2018: Updated to use get_upload_dir()
method instead of wp_upload_dir()
.
November 19th, 2016: Fixed typo in method name.
October 24, 2016: Fixed issue with Gravity Forms 2.0.7. Major refactor. Requires Gravity Forms 2.0.7.15 or greater.
December 5, 2015: Added support for Post Image fields.
September 22, 2015: Updated to remove forward and backslashes from new filename.
March 26, 2015: Fixed issue when submitting form with no uploaded files
Stop! There's a better way.
This snippet is available as a plugin with Gravity Perks, a suite of over 47 premium Gravity Forms plugins!
We wrote a snippet that will allow you to create a dynamic naming template for your uploaded Gravity Form files. This includes the ability to prepend, append or generate from scratch custom file names. You can use merge tags to include user input in your new file names.
Here are a couple use cases where this snippet might be useful:
- Include the name of the submitting user either before or after the file name.
- Include an event name in the file name to better categorize which files belong to which events.
For example, given an original file name of mountains.png and a template of {Name (First):1.3}-{Name (Last):1.6}-{filename}
, the final image name would be Jordan-Smith-mountains.png
Getting Started
- Check requirements
- Make sure you have Gravity Forms installed and activated.
- Already have a license? Download Latest Gravity Forms
- Need a license? Buy Gravity Forms
- Make sure you have Gravity Forms installed and activated.
- Install the snippet
- Copy and paste the entire snippet into your theme’s functions.php file.
- Configure the snippet
- Once you have installed the snippet, find the snippet configuration section located at the bottom of the snippet code.
- Replace the
form_id
with the ID of your form. - Replace the
field_id
with the field ID of your File Upload field. - Replace the
template
with your custom file name template.
Usage Examples
First and Last Name
new GW_Rename_Uploaded_Files( array(
'form_id' => 628,
'field_id' => 3,
'template' => '{Name (First):1.3}-{Name (Last):1.6}-{filename}', // most merge tags are supported, original file extension is preserved
) );
In this example, we are prepending the first and last name from the form to easily identify who submitted the file. Most merge tags are supported using this method and the original file extension is preserved.
Form Title Merge Tag
new GW_Rename_Uploaded_Files( array(
'form_id' => 12,
'field_id' => 18,
'template' => '{form_title}-{filename}', // most merge tags are supported, original file extension is preserved
) );
In this example, we are prepending the title of the form to the filename to quickly identify which form the file was uploaded to.
Static Text
new GW_Rename_Uploaded_Files( array(
'form_id' => 628,
'field_id' => 5,
'template' => 'static-file-name',
) );
You can use any text you’d like, just make sure to add the {filename}
merge tag somewhere in there.
Ignore Extension
new GW_Rename_Uploaded_Files( array(
'form_id' => 628,
'field_id' => 5,
'template' => 'static-file-name',
'ignore_extension' => true,
) );
By default, this snippet takes the extension into consideration when renaming files. For example, static-file-name.jpg
is different from static-file-name.png
. You can change this behavior to ignore the extension of a file so in this scenario static-file-name.png
would be renamed to static-file-name1.png
as there’s already a static-file-name
file uploaded.
Parameters
form_id (integer) (required)
Your Form ID. There is no default value.
field_id (integer) (required)
The Field ID of the file upload field. There is no default value.
template (string or merge tag) (required)
This is the template that controls how the file will be rewritten. The value can be either a static string or a merge-tag(s). There is no default value.
You never need to include the file extension in your template. It will automatically be included.
Was this helpful?
We hope you find this snippet useful! If you do, show us some love by sharing this article on the social media platform of your choice. Let’s keep the Gravity Wiz pumping out awesome snippets. Thanks!
Hi, There is a way to have the file displayed with the file name but without hyphens. I mean leave the spaces blank.
Edgar, you can’t have a white space in a filename, because WordPress would replace it with a dash and it will also sanitize any special character including brackets by removing them.
Hello,
I’m experiencing an issue with filenames containing UTF-8 characters, such as Persian or Arabic characters. When uploaded, these characters are being replaced with unknown characters. Could you please enhance this code to support UTF-8 characters? Your assistance with this matter would be greatly appreciated.
Thank you in advance.
Hi Saman,
I’ve been unable to reproduce this issue when testing locally. If you have a Gravity Wiz license, we’ll be happy to dig into this. Drop us a line.
Bonjour Merci pour cette explication et ce code qui fonctionne parfaitement ! Il renomme bien mes fichiers qui sont hébergés sur mon site par contre lors de la validation de mon formulaire gravity form en ligne une notification part vers les intéressés en joignant un fichier zip avec tous les fichiers ! Là mon problème c’est que ces fichiers ne sont malheureusement renommés ! connaissez vous une solution à ce problème ? Il faudrait que la modification du nom se fasse dès que la personne joint sa pièce jointe au formulaire et pas au moment de l’envoie je pense ! merci par avance
Hi Anthony,
I’m not able to reproduce this issue when I test locally. If you’re a Gravity Perks customer, we’re happy to dig into this further. Drop us a line.
Hi- Thanks for the snippet! The one issue I’m having is that the {filename} merge tag you reference in the examples doesn’t carry over to the new filename, like in the ‘mountains.png’ example above.
Filename prior to upload: aJ19p_So.pdf
new GW_Rename_Uploaded_Files( array( ‘form_id’ => 2, ‘field_id’ => 32, // most merge tags are supported, original file extension is preserved ‘template’ => ‘2_{filename}’, ) );
Resulting filename: 2_filename.pdf
I feel like I’m missing something really obvious here…
Thanks! Spencer
Hi Spencer,
You aren’t missing anything. I can confirm the issue with the {filename} merge tag. I’m forwarding this to our developers to look into this. Please expect an update to this comment when this is fixed.
Best,
How can I programmatically populate a hidden field value (based on values submitted on other fields), in a way that the hidden field will be populated and used in the rename template?
i.e. Field One (ID:1) – user will submit a value Field Two (ID:2, hidden) – my code will calculate this value based on the user submission
‘template’ => ‘{Field Two:2} xyz’
I have tried using different actions and filters with different priority paramters, but to no avail…. please help.
Hi Ofra,
You can use our GP Populate Anything Perk to populate the Hidden field based on the value in the other field. I will also suggest using our GP File Renamer Perk to rename the files instead of using this snippet.
Best,
Hello,
I’m using WPCode and it works when I only put two parts of configurations.
new GW_Rename_Uploaded_Files( array( ‘form_id’ => 1, ‘field_id’ => 16, // most merge tags are supported, original file extension is preserved ‘template’ => ‘{entry_id}/{filename}’, // Ignore extension when renaming files and keep them in sequence (e.g. a.jpg, a1.png, a2.pdf etc.) ‘ignore_extension’ => false, ) );
new GW_Rename_Uploaded_Files( array( ‘form_id’ => 1, ‘field_id’ => 22, // most merge tags are supported, original file extension is preserved ‘template’ => ‘{entry_id}/{filename}’, // Ignore extension when renaming files and keep them in sequence (e.g. a.jpg, a1.png, a2.pdf etc.) ‘ignore_extension’ => false, ) );
But when I put all my code into the snippet, it will show “We encountered an error activating your snippet, please check the syntax and try again.” “Snippet not activated, the following error was encountered: syntax error, unexpected ‘ ‘ (T_STRING), expecting ‘)'”
I’m not sure is there any problem with my code or it’s the plugin’s problem?
The complete code is show in the link below
https://codeshare.io/lorlmB
Hi,
The complete code snippet is correct and shouldn’t cause any error message. The error message you’re receiving shows that you’re missing a closing brace. Can you copy and paste the code again and see if it helps?
Best,
Hi Samuel,
I copied and pasted it again, the error message is still the same @@
Hi
Can you try this code and see if it works for you?
Best,
Hi Samuel ~
Yes, it works now!
But I cannot find the differences in the two codes
So maybe I shoud edit the code in notepad and paste it into WPCode
Thanks for your help again
You’re welcome. Yes, there is no difference between the two codes. However, when I pasted the code into a code editor, it showed some unwanted characters that I had to remove to get it working.
Best,
Thanks for a great plugin. I would like the image the user uploads to be named after the role it is a member of and saved to a folder.
It should be saved in /wp-content/uploads/company/ and named rolename.jpg . Is this possible?
I’m using ultimate member, so I’ve tried several different ways like these shortcodes: ‘template’ => ‘{um_display_role}’, ‘template’ => ‘[um_display_role]’, But then only the file name will be um_display_role.jpg.
If the role is named company, then I want the file to be saved as company.jpg . If the file already exists, I want it to be overwritten and of course only saved in /wp-content/uploads/company/ .
Can you help me with that?
Hi Robin,
The {um_display_role} shortcode wouldn’t work when used as the value for the template parameter. What you can do is to dynamically populate a hidden field on the form with the role of the user and then use the merge tag of the hidden field as the value for the template parameter to rename the file with the user role.
Best,
When I add the snippet through code snippets plugin it is showing the following error: The code snippet you are trying to save produced a fatal error on line 1:
Uncaught Error: Class ‘GW_Rename_Uploaded_Files’ not found in /home/XXXX…..
Did I miss something?
Hi Omar!
Thanks for your comment. We are sorry you are facing this issue with our snippet.
We would like to take a look at your snippet added through the Code Snippet plugin. If you have a Gravity Perks license, can you get in touch with us via our support form?
Hello, how to avoid changing the name with a number in the same extension, or rather how to rename again and again the same file with the same extension.
Example: Want to avoid this: a.jpg, a1.jpg, a2.jpg.
You want to achieve this: a.jpg, a.jpg, a.jpg, a.jpg
Hi Arden,
It seems this is not currently supported and it will require some customization. If you have a Gravity Perks license, can you get in touch with us via our support form?
Cheers,
Does this work with the Dropbox Upload extension?
Also, does it work when ‘multiple uploads’ is enabled?
Hi Todd,
It should work when multiple uploads are enabled. About the dropbox add on integration tou can get in touch with us via our support form if you have an active Gravity Perks license, so we can take a look at your setup and assist you to set it up.
Hi this snippet looks great how to rename 2 or more files in the same form
Hi Jasim,
To rename two or more files on the same form, you have to duplicate the configuration and update the IDs accordingly. Here is an article with details on how to do this.
Best,
Hi
Thank you for the plugin
Ive Installed the plugin and just just wanted to find out
How do i add white space or brackets?
Thank you
Hi Muhammed,
You can’t have a white space in a filename, because WordPress would replace it with a dash and it will also sanitize any special character including brackets by removing them.
Best,
Hello. This is a great snippet, thanks so much for making it available. I do have one issue, though:
I am prepending unique identifiers to file names in files uploaded by customers. That part is working great. However, administrators utilize GravityView to access the same form wherein they will occasionally make an edit to other entries. When that happens, even if it’s an edit to a totally unrelated entry, the renamed files get renamed all over again. For example, a file may start out as IMG1000.jpg, it gets uploaded and renamed to unique_identifier_IMG1000.jpg, but then it gets renamed yet again to unique_identifier_unique_identifier_IMG1000.jpg if the administrator edits any entry in the form. Is there a way to prevent this renaming duplication from happening? Thanks in advance for your help.
Hi,
I am unable to recreate this issue so I have sent you an email to request more information. Please check and reply.
Best,
Doesn’t work.
Error thrown Class ‘GW_Rename_Uploaded_Files’ not found
Hi D,
Based on the description of the error. It seems the snippet was not installed. How do I install a snippet?.
If you have any further questions and you have an active license, you can get in touch with us via our support form.
Cheers,
Hi, I have more than 20 forms and each of them allows to upload up to 5 images, is it possible to make the code dynamic so that it works throughout the site? Or are there other solutions (apart from having to maintain 100 different snippets).
Thanks, Nicola
Hi Nicola,
If you want to use the file rename snippet on more than one file upload field and on multiple forms, you only have to set up multiple configurations. You don’t have to duplicate the entire snippet, but just the configuration part which will create multiple instances of the Class. Here is an article on how to apply a class-based snippet multiple times.
I hope this helps.
Best,
Can anyone think of a way i can get the category slug instead of the category name? This is for a contest entry, so to make a random number, I’m grabbing some mixed up time stamp. ($result = $date->format(‘uYHmids’);)
‘template’ => ‘{Category:9}-‘.$result,
Field 9 on my form is the Post field Category, but i’d prefer to pull in the slug instead Could there be a hidden field on the form maybe that i could use to populate with the category slug once the user fills in the Category field?
Or any other thoughts?
J A
Hi there,
You could populate a hidden field with the category slug using Populate Anything. To do this, you need to filter the category based on the selection made in the Post Category field. If you have questions, feel free to reach out to support.
as per initial comment – how do we use on more than one form? is that possible – appears you can set multiple configurations but not sure if that is just that part of the code or does all of the code require duplication with appropriate settings – got it to work with form A) now want to also use for form B) – thanks in advance – cool snippet (appreciate the share)
Hi Steve,
To use the snippet on more than one form, you only have to set up multiple configurations. You don’t have to duplicate the entire code. You can read more about here.
Question: How do I modify this to include multiple instances. I have one form with 3 different file upload fields. Need different naming conventions for each field.
Hi,
We’ve already followed up via email. If you have more than one field per form, you will need to create as many configurations as fields you have.
Best,
I have a question
When I add the code in function.php file, it’s work correctly and rename any file i Upload it
but it’s work only when i create new gravity form with file upload
old forms i was created before add the code it’s not work its rename a file like name-first1-3.jpg
how can i make the code work with old form i have ?
Hi Mohamed,
That’s strange because the snippet should work on old forms without any issue. You may want to check the configuration to see if you’re passing the right parameters. In case it’s still not working, you can get in touch with us via our support form if you have an active Gravity Perks license, so we can dig into this further.
Best,
Hello!
Nice option. I want added :ymd to the date into the code. But is it true that this is not supported? It’s looks like this: {Expiry date:39:ymd}
Thank you.
Hi Patrick,
That wouldn’t work. The output format for a Date field’s merge tag is set by the Date Format option in the field settings. Change this to yyy-mm-dd and the file will be renamed accordingly. You can’t also have slashes in the file name so this format, yyyy/mm/dd, won’t work.
Best.
Hi Guys, i don’t understand this point?
“Replace the template with your custom file name template.”
Hi Shak,
That is the configuration for the snippet. You’re to replace or update the value for the template key with the name you want to use to rename the file. If you’ll be getting the name from another field on the form, then you’ll update the ID of the merge tags accordingly.
I hope this helps.
Best,
Hi. Can I use this snippet to prepend a merge tag, such as username for a logged in user, to the original filename? I need to retain the original filename.
Thanks
Hi Chris,
This should be possible if you populate the username into a field on the form. You can then use a configuration like what’s below to prepend the Username to the filename.
new GW_Rename_Uploaded_Files( array( 'form_id' => 628, 'field_id' => 3, 'template' => '{Username:10}{filename}', ) );
Thanks so much for this!!
Hi, I have 3 upload fields in 1 forms and want to rename each files with format: file1-001, file2-002, file3-003 . Could the snippet do that? and how to modify the snippet?
Hi Alphan,
This should be possible with the snippet. You’ll create three copies of the snippet configuration, and set them up to target each of the file upload fields. Here is documentation on how to apply a snippet to more than one field.
Best,
Is there a way to modify this script so that it looks at updated Upload paths?
I’m changing the path using this hook: https://docs.gravityforms.com/gform_upload_path/
When I add the filter, it doesn’t rename the file. If I comment out the
add_filter
line on the path change, the rename works just fine.Hi Tim,
This snippet is compatible with the
gform_upload_path
filter. Are you using the latest version from our Snippet Library?Hey, Scott – Yes, I’m using the latest version of the snippet.
Additional info that may be useful – the redirected folder is not in web root — it’s confidential data, so we’re auto-saving it to an external mount —
/share
(as an example) — I’ve also removed the URL in the upload path redirect code as there won’t be a path that’s accessible from the dashboard or email.Hope that helps clarify.
Hey Tim, responded to your ticket but sharing here for other folks. Setting the
url
via thegform_upload_path
resolved this issue for me.Where is the filter for the gform_upload_path supposed to go, to make this work right? I have a multi-form field on my form (set with max 1 upload). The filter currently is place in the init() function like this, but it does not work for me
Hi,
I’m guessing the filter snippet stands on its own. You can use the snippet David shared above without adding it to the Rename Uploaded files snippet. However, if you want to customize the Rename Uploaded files snippet with this filter, then we’ll need to forward this to our developers. If you have an active Gravity Perks Pro license you get in touch with us via our support form so our developers can take a look at your request.
Best,
Thanks Samuel, it does work when placed outside of the class. Dont know why i was trying to over complicate things.
Hi,
You’re welcome.
Best,
Hello! Can you give the front end user to rename their files as they see them on the uploads? While using Uploads Pro, you can see the previews of each image, as they load, along with the file name. It would be great to be able to have a pencil icon next to the file name, to be able to quickly rename that file. Can you help?
Hi Austin,
This is currently not supported and we don’t have a snippet for this. I will forward this to our developers as a feature request.
Best,
Hi, This is great, thank you!
Is it possible to change a merge field to lowercase when assigning the template? something like this:
‘template’ => strtolower(‘{:3}’),
Also, when an image with the same name is uploaded, a number are automatically added. is it possible to add a – before the number so it reads image-1.jpg and not image1.jpg
Hi Schalk,
Changing the merge field to lowercase wouldn’t work like that. The template parameter expects a static value or a merge tag. You’ll have to change the field value to lowercase after submission but before the entry is created so that the merge tag picks up the lowercase value.
To add a dash when there is an image with the same name, you’ll have to customize the snippet. If you have an active Gravity Perks License, you can get in touch with us via our support form, so our developers can take a look into this.
Best,
Thank you GW team! I kept getting issues with similar filenames being uploaded into S3 and getting unpredictable filenames for referencing. This has cleaned that up for me…much appreciated.
Awesome, Matt! And great use-case for this snippet. 👌
Is this feature available as a plugin with Gravity Perks?
Hi Jordan,
This tutorial is available as a snippet. You can use it in combination with GF Media Library Perk and GF File Upload Pro Perk
Best,
Hi Everyone,
I am trying to get the date to appear in the name of the my uploaded file, I tried using the merge tag of {Date:3}, {Date:3.1} (and .2 / .3) and {Date:3:value}, I am not wanting the date to appear as a date of 2/8/2021, but 2021-02-08 would be perfect, this way my client can see images in date order for example.
Any thoughts?
Thanks!
Ken
I forgot to add, I am getting the year with the Date:3 and Date:3:value merge tags.
Ken
Hi Ken,
The output format for a Date field’s merge tag is set by the Date Format option in the field settings. Change this to yyy-mm-dd and the file will be renamed accordingly.
Very useful code!
Is it possible to strip out special characters from the merge tags? I have a PHP function that does that, but can I insert PHP that calls a function inside your code snippet or will it break it?
BTW I got 3 gravity perks last week, the nested forms rock!
What you can do is extend our class with your own and then modify the clean function to do any kind of sanitization you want.
class Your_Rename_Uploaded_Files extends GW_Rename_Uploaded_Files { function clean( $str ) { return $str; } }
Thanks for this code – it’s been really useful!
I’ve been having an issue recently where a small number of files renamed using this snippet end up being saved as zero bytes in size.
There’s no obvious pattern to the affected files themselves, and in some cases the issue affects only a subset of files uploaded along with a single form submission.
I see no errors in the Apache or PHP logs that could shed light on the problem, and I haven’t been able to reproduce the problem myself. My best guess right now is that renaming is sometimes kicking in before the file uploads have finished, perhaps due to load on the server – is that a possibility?
If so, is there any way to ensure the uploads are definitely complete before renaming triggers? (Even just a way to ensure the original file isn’t lost would be helpful; I can’t find them in GF’s temporary upload folder.) And if not, can you think of any other explanations?
Thanks,
Hi Ben,
I haven’t experienced such before so I’m guessing this is an issue related to your server. You may want to check out our GP Media Library Perk, which enables the feature to automatically import uploaded files to the WordPress Media Library when the form is submitted. This can help ensure that you don’t lose any uploaded files in case you don’t find them in the GF Temporary upload folder.
Best,
can you use this with Slim Image Cropper?
Hello Alex, this is something that we would have to look into and see if we can work within the code. If you are a a Gravity Perks user, go ahead and leave us a message through our support page found here.
Hi,
When I’m pasting this snippet into my functions.php file I’m getting an error:
“There has been a critical error on your website. Please check your site admin email inbox for instructions.
Learn more about debugging in WordPress.”
how come? Do I need to change something more else than the bottom part?
Kind regards, Vincent
Hi Stephan,
It sounds like you might be having some trouble with installing the snippet. Please refer to our article on snippet troubleshooting for details on installing our snippets.
https://gravitywiz.com/documentation/snippet-troubleshooting/
However, if you’re a Gravity Perks Subscriber and you still experience issues installing the snippet, you can send us a message via our support form so we can take a closer look into it.
I hope this helps.
Best,
Hi Samuel,
Got it, thanks. And if you want to rename the file to a field other then the name? How could u achieve this?
Kind regards,
Hi Stephan,
Set the template parameter to the merge tag of the field you want to use its value to rename the file
'template' => '{:23}'
Best,
Like one of the replies above, I have multi site, so I cant add the code above to my functions as it will interfere with other GF’s. I tried using code snippet plugin but it throws an error. Do you have any other suggestion? On the functions file, Is there a way to check for site ID and then apply the code?
Hi Albert,
You can get the Current site/blog ID with this
get_current_blog_id();
, you can then put the snippet configuration inside an if statement to check if the current site id is equal to the ID of the site you want to target. Something like this should work for you.if (get_current_blog_id() == 4 ){ new GW_Rename_Uploaded_Files( array( 'form_id' => 628, 'field_id' => 3, 'template' => '{Name (First):1.3}-{Name (Last):1.6}-{filename}' ) ); }
I hope this helps.
Best,
Thanks for the clear instructions. It’s works on one image. In my form I have more than one image to be renamed. Do I need to use the whole code snippet each time for a new FieldID in the same form? Example Form ID is the same, Field ID changes, and naming works as your above instructions.
In fact, I’d like to use the snippet once and the rename instruction multiple times and for different forms. Is this possible? Then I just concentrate the renaming functionality in one place.
Thanks
Hi Stuart,
If you want to use the file rename snippet on more than one file upload field, you can create multiple copies of just the configuration. You don’t have to duplicate the entire snippet, but just the configuration part which will create multiple instances of the Class. Here is an article on how to apply a class-based snippet multiple times.
Best,
I have 4 file upload fields per form entry. Each of these 4 upload fields are multi upload.
I would want file name to be “Postage[EntryID]X” Where entry ID is the form entry ID and X is the upload number, so first upload is 1, then 2 etc.
How do I go about that (a bit confused because I have multi-upload and multiple fields? Thanks
Hi Chelsea,
You can use the
{entry_id}
merge tag to insert the entry ID into the renamed file, however numbering the files inside a multi-upload field isn’t currently supported.What you could do instead is use GF Nested Forms with a Single File upload field inside the Nested Form. You could then use the :count merge tag modifier in a field in the Nested Form to count the number of uploaded files, as shown in this article.
I have a WP Multisite set up with http://www.mainsite.com/subsite/... format. I have plugins for Gravity Forms and Wp DataTables with Gravity Forms integration. I also have the Gravity Perks installed. My sub-sites are designed for separate use/access by separate clients. The sub-sites each have a number of Gravity Forms that are ‘checklists’ collecting info on different things. A number of the forms are checklists for reviewing documents and they have a file upload field to enable the client to upload a pdf copy of the document that they reviewed.
Can this snippet be applied to work on a Multi-site set up for a number of different forms each with a file upload field?
On each form I use the GF Perks Unique ID to create a unique sequential number for each submitted form. Is it possible for the upload file to be include this in the new file name?
For example a file to be renamed as “XX00123Company Name” where XX00123 is the Unique ID sequential number and Company Name is the value input for a given company name field in the form.
As I say I will have another separate form for, say, a legal document checklist with another Unique ID, say. “LG001” and, say, a document title name field, say, “Trust Deed” that I would want the file upload to be saves as “LG001_Trust Deed” .
As I am using WP Multisite I can See Gravity is already storing the upload files in the gravity form folders under separate site number folders. I would however like to avoid it creating its subfolders for Year and Month of submission. ( I know there is another snippet for defining the path which I ope to use for this)
How can I apply your snippet on Multisite and for different forms? Am I right in thinking the functions.PHP sits at Network level so I think I need the snippet to take account of the site number to ensure the files are save in the folders for each site?
I would be grateful for your advice
Hi Chris,
This snippet supports GF Unique ID. Simply insert the merge tag for your Unique ID field in the
template
parameter.Instead of installing the snippet Network wide, I suggest using the Code Snippets plugin to manage the snippets on a per-site basis.
Amazing bit of code, its helping me out massively. THANK YOU!
I have a question, is it possible to pass a user input on the form into the filename?
For example, user enters an order number and uploads a file, the filename includes the order number?
Kind Regards
Hi Matt,
Most Merge tags are supported, so this should be possible if you update the template parameter in the configuration with the merge tag of the Order Number field. Something like this should get it working
'template' => '{OrderNumber:113}-{filename}'
Best,
Thanks Samuel,
Can you quickly confirm the following, in the string: {OrderNumber:113}-{filename}
What does the “:113” refer to? Is it the form field ID?
Kind Regards
Matt PS. many thanks for a super quick response on the last thread!
Hi Matt,
113 is the Field ID for the Order Number field. You may want to check out this documentation to get a better understanding of merge tags.
Best,
I’m trying to add different values from the form but don’t know the syntax to. The info i’m trying to add is “Event” and “Year”. When I tried to copy the example with form_title or even {Event:value} like a comment suggested, I just got “Eventvalue-last-first-file”. Any suggestions?
Never mind I got it. I had to put the form id with the event, so {Event:2:value}. worked perfectly
Hey Jerry, Super happy to hear this was resolved. 😃
Hi, I found if field value (merge tag) is Chinese string, the final filename will display alphabet instead Chinese. How could I resolve this?
Hello Danny, This is an interesting question. What language is your website currently set to within the WordPress/Database settings? Let us know.😃
Hi Ryan, my WordPress website language is set to Traditional Chinese, MySQL Database is set to UTF-8 Unicode (utf8mb4).
If the field value is “一二三” ( it means 123 in Chinese), then final filename will display “yyy”. If there is 3 Chinese words, it will become 3 y.
Hello! How to use cyrillic in this snippet?
Hello Ivan, Could you elaborate on your use case? That would help to see if we have a solution for this. Thank you!
Holy *&**$$@ !!!! –
Thank you so much for adding this snippet. It is such a timesaver! We rely heavily on GF for some of our inventory duties and you just saved us literally hundreds of hours per year.
Thank you sincerely for your time and willingness to share this AMAZING bit of code.
A Million Thanks. Take Care.
Glad to help, Chad! 😃
Hi David… I’m pretty new to GF and I added your file upload renaming code & works like a champ.. (Thank you!!) However, when it comes to Multiple Instances, Same Form – (2 different file uploads / same form) where am I adding the code you supplied for the class snippet?? I assumed I would add it in functions.php where the original renaming config code was, but that errored out. Any advice or instructions would be greatly appreciated! Thanks!!
Hi Kenny, this will help: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/ ?
Hi David,
Thanks for the quick response! And I looked at those snippets earlier & tried adding them, to our form (functions.php) and couldn’t get it to work. Got errors, mainly because I wasn’t sure where those “Class Snippets” should be placed in the code… (Sorry for any confusion) Could you please show me where they should go along with the code above?? Just lost over here… Thank you!!
It save to many sub folder and rename the file as 2019.pdf :( how can I change this in the code?
Hi Ishato, I’m not sure I understand. Could you elaborate?
I have a photo upload form where I direct people to name the photos in the order they want them displayed, ex: 1.jpg, 2.jpg etc.
By default, multiple uploads of 1.jpg and 2.jpg etc will be renamed 11.jpg, 21.jpg etc.
I thought I could use this function with the Gravity Wiz Unique ID add on to uniquely name the files as 00011-1.jpg etc, but it still adds on numbers to the filename on submission.
Is there a way to use this function to keep the order without adding on an additional number for duplicate file names?
Hi Kris, this should work but I believe there are still files in the folder with the original 1.jpg, 2.jpg, etc names. If you remove those original files, this should work moving forward.
Hi David – thanks for the reply. I’m trying to use this solution to uniquely rename uploaded files because users will upload files with the same name. So user1 could upload photo1.jpg and user2 could also upload photo1.jpg.
I was hoping to use this function with GW’s unique id to rename them but it looks like it renames them but after the default rename that happens when multiple files get uploaded with the same name. So I lose the original name. Does that make sense?
I’m using Gravity forms to extend Woocommerce, is there a way to add the order number to the file name before uploading?
Hi Gary, I’m not sure. Likely not without customization/extension of the snippet. I’d check with the developer and see if he is storing the order ID in the entry meta.
How do you use this on multiple file fields or forms within the same wordpress site ?
This will help: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
Thanks for the quick reply. That did the trick.
anyone get this to work with Slim uploader ? (https://pqina.nl/slim/)
how to make write file name turkish characters? UTF-8
i need ŞşĞğÜüİiÇçÖöIı
please help
what if I have a form field for a stock number “SU438125” and from that stock number I upload 8 vehicle photos and I want them to be renamed: SU438125_1.jpg SU438125_2.jpg SU438125_3.jpg SU438125_4.jpg SU438125_5.jpg SU438125_6.jpg SU438125_7.jpg SU438125_8.jpg
is this possible?
Hi Tim, it should auto-enumerate the filenames. The tricky part will be getting the “1” on the first one…
This is great! Is it possible to tweak the snippet so it also work with recordings uploaded with the Gravity forms Pipe addon?
We haven’t tested this scenario but we’re happy to add it as a feature request.
I asked this before with no reply, but has anyone noticed that GF 2.4.8 or better breaks this function. I have the latest code installed. The files do upload to proper folder but do not rename. Help!
Well, turns out that GF version was not the issue but rather WP 5.*. I have a function that allows me to specify the upload folder by form id. So when the rename function tried to do it’s thing it was getting all confused because it tried to use the default upload path. Because of this, you can’t use the GFFormsModel::get_physical_file_path function. It actually did nothing due to the incorrect path vs url problem.
Took me a long time to debug it…but finally did. I fixed it by creating my own $this->_get_physical_file_path function:
http://snippi.com/s/uu1ctgf
I then replaced calls to the GFFormsModel one in the rename_uploaded_files function and it all started working again.:)
http://snippi.com/s/fzxwoko
Hi Sean, this is still working for me with the latest version of Gravity Forms.
Issue is that somewhere along the way over the last few month something changed that is causing the rename functions to not recognized the true upload path and is defaulting. I fixed the code, see my previous reply.
This is great, but any chance you could extend this functionality so that it applies to any form and/or any form upload fields, so that I can add, say, a timestamp to the end of each file upload, or a random number, etc.?
Thanks, Adam
Hi Adam, try not specifying a “form_id” or “field_id” parameter.
No, unfortunately, that doesn’t work. Execution stops at is_applicable_form (line 54) and returns an uninitialized $entry. Any idea how this could be adapted to apply to all forms and upload fields?
It might be helpful if we could add the field (admin) label, maybe another path?
@Antoone – we’ve needed the admin label (value) for one of our forms as well. We have competitors uploading an .mp3 file to use as part of a performance and need those files renamed to match the division and name of the competitor.
Here’s what works for us to populate the admin value instead of the field label for the ‘Division’ component of the naming.
‘template’ => ‘{Division:2:value}-{Name (First):3.3}-{Name (Last):3.6}’
Essentially, put :value trailing the field reference.
Hi I was redirected here from GF. My question relates to a file upload from the front end when and used by non-technical staff. I have a member of staff who generates a pdf file containing the latest information, they will then upload to wp, and when the page is next called in wp it uses the latest pdf file. The issue I have is that when GF uploads the file because one already exists by that name a suffix is added to the file being uploaded, which of course means the wp page does not open the new file. GF suggest that this snippit might do the trick. I’m already a GW client using the Populate Anywhere perp. Thanks Michael
Hi Michael, it sounds like what you want to do is overwrite the previously uploaded file with the new file? Is that correct? If so, this snippet will not be much help as it would still append the suffix as to not overwrite the existing file.
Hi Dave
Yes that is correct. Do you know of such a solution please, I thought it would have been a common need but have carried out a number of googles without success – but being a newbie to WP et al I might be asking the wrong question. Thanks Michael
Thanks, that’s great !
I’m currently hacking this code to run it for any form that have one or more upload fields. Therefore I modified is_applicable_form & is_applicable_field functions : http://snippi.com/s/9w1f0jc (note : with these hacks, form_id and field_id parameters won’t be used anymore) Seems to work as a POC, but maybe you’d like to refine/correct it ?
What I’d like also is to set the template parameter so that the field name is added among – say- last name field and original filename. Can I use a “merge tag” like in parameters array or should I hack later, while in the loop ?
Hi Antoine, first, I’d recommend extending the class rather than modifying it. This way you can overwrite the functions you want and still replace the base class with newer versions as they become available. Here’s an example:
http://snippi.com/s/c7wnilw
I’m not sure I understand what you’re trying to do with the field name and template parameter?
Hi David, thank you for these helpful comments. Still a bit fresh on php/wp but I’ll certainly extend V.S modify the code.
What we might have on a single form is multiple upload fields for different usages, say a personal photo and an ID scan. We’d like to be able to identify each like : [form field name]-{firstname}-{lastname}-{filename}.
Also, I noticed that my hack has a flaw; the form will be submitted (and confirmation sent) as many times as there are upload fields in the form. Sure have to add some controls to prevent this … any idea ?
HI David, as mentioned above, I’m facing a problem I cannot solve by myself. If my form contains more than one fileupload field, everything seems to be ok but the confirmation message is sent as many times than there are fields.
I’ve been trying several combinations, hooking on gform_disable_notification filter with no luck, I’m probably missing something obvious here …
Basically, what I do is : 1. In the parameters array, I’ve added a “field_nb” parameter (defaulted to 0) 2. In the “is_applicable_form” function, while looping into the fields to find (eventually) fileupload file types, I increment this parameter so that we know how many fields should be treated before sending notification. 3. I tried various combinations I’m to shameful to share here (hooking on gform_disable_notification) with no luck … Basically I just wanted to switch notification for this particular entry off by default and reactivate it (in the ‘foreach’ fields loop) only for the last field. I guess I’ve reached my limit here … help very welcome :)
David, I’m really sorry for flooding (and my poor English). This will meant more than my words : http://snippi.com/s/darpu4y
State : I can disable notification, can’t enable it back …
GF 2.4.8 breaks this function. I had to roll back to 2.4.6. Anyone else experience this?
Sean
MERCI BIEN; est ce que existe une extension pour ce la?
This is working great. Just one question to see if this is possible. Would it be possible to change the file name AND convert to uppercase in the process? I have a field in GF that I’ve converted to uppercase before saving in the db. This field is also being used to create a query string that gets passed to the form where the file upload and renaming happens. This query string doesn’t use the uppercase value saved in the database but rather whatever the user put in.
Thanks!
Hi Zachariah, your best bet is to modify the clean() method to also uppercase the string.
I’d like to be able to pull from the ‘admin value’ instead of the ‘label’. We have the label descriptive to show on the front end to the user, but an abbreviated version for renaming and admin purposes is better.
How to get the ‘value’ instead of the ‘label’?
Hi, is it possible to use this code with the “gform_upload_path” filter?
I want to change the path and rename the file.
Regards, Michael
Yup, this is compatible with that filter. ?
Hi,
when creating directories by using “/” on the templates there is a case that is not handled correctly by version 2.5. As our website serves German and international audiences, our field names are like “Company / Firma”. This leads to a mere tag like “{Company / Firma:1}” and the slash within the brackets is also interpreted to crate a directory – but should not.
Do you see chance to make the script in this regard bullet-proof? It would be great!
Kind regards in advance, Martin
Is it possible to modify this code to create new folders the upload folder for an uploader?
field_1/field_2/file.txt
That sort of thing?
If by field_1/field_2 you are referencing the values entered into these fields, yes, just include the merge tag for that field in the “template” parameter.
'template' => '{My Field:1}/{My Other Field:2}/{filename}'
I tried to add a slash to create subfolder but it did not work. Is it because a slash only works between {fields}?
What I did:
{Markenname:7} – {entry_id}/Logo/{filename} and {Markenname:7} – {entry_id}/Pictures/{filename}
Any idea?
Hi David, I found out that I had an older version running.. with V 2.5 the directory creation works. Just one prob – I will post another “fresh” comment. Kind regards, Martin
Hello, when I upload images from file upload field, the images are not shown in the media library. what should I do to images being displayed there. I need it and looking forward to an answer. Thank you.
This will help: https://gravitywiz.com/documentation/gravity-forms-media-library/
Isn’t there any way to write a code for that. I can’t use plugin. Thanks
actually, I am using gravity form with ACF and I want when users upload image for gallery field, the images being related to the gallery. or at least the images be displayed at media library.
Hi, I have so many forms on my site, many of which have file uploads that I would like to customize filenames for. Is there a way to configure this for ALL forms, instead of applying to specific forms?
Thanks in advance.
This is not currently supported. The primary hold-up right now is that you must specify the field ID which typically is not the same across multiple forms.
That’s unfortunate. Thanks for the response Dave.
I don’t understand how this is working, I must missing something.
Where does {Name (First):1.3}-{Name (Last):1.6 come from, how can I relate this to my form? is this the name of the input field? what does 1.3 and 1.6 relate too?
Hi Dan, they are merge tags that you will need to manually enter. At a minimum a merge tag must include the field ID (and input ID for multi-input fields). The merge tag for a field of ID 1 could be as simple as
{:1}
. The merge tag for the first name input of a field with ID 2 would be{:2.3}
where 2 is the field ID and 3 is the input ID.Hi,
First, thanks for that great snippet. I install it and its works great.
But, after i added it, there was a strange hitch. The gravity forms can not export records of the forms to the file. Instead it displays them on the browser.
Do you know this problem? How do I fix it?
Ravid
Hi Ravid, I configured the snippet, submitted an entry and exported that entry without issue. It sounds like there might be some other conflict on your end. I’d try a theme/plugin conflict test to start: https://docs.gravityforms.com/testing-for-a-themeplugin-conflict/
Great snippet David! This will come very handy for an ongoing project. I’m scratching my head regarding two things 1. the implementation; In the instructions it is mentioned to copy and paste the entire snippet into the theme’s functions.php file. That means even the php opening tag? 2. Would this snippet work with multiple upload files in a form? Exemple adding to the configuration array ‘field_id’ => 5, 22, 35
Please ignore the point regarding implementation. I found the necessary instruction on a previous post of yours.
Hi Dritan, you will need to create an new “instance” for each field. More details here: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
Excellent! Thank you David
Hi. How can I include the © symbol in the file name? It gets lost once the file is uploaded. Thank you!
Hi Albert, it is most likely being stripped out in the clean() method. You can modify this to be less strict.
Hi David, I am trying to use this with a 3rd party upload add-on ( not the default file upload by GF ) Could you put me in the right direction to change the snippet to work for https://codecanyon.net/item/slim-image-cropper-for-gravity-forms/19606752
Thank you, Schalk
That’s a very complicated question. I wouldn’t know without doing a significant amount of digging into that plugins code.
Will this work with Gravity Forms 2.3?
Yup!
Is there a way to have the renaming script pull the ‘value’ instead of the ‘label’ for each of the fields reference in the script?
The front-end option needs to be descriptive so the person uploading the file has clarity, but the back-end label can be abbreviated to keep filenames short to make life easy for the admin.
Hi Thad, unfortunately, this is not possible without significant customization. You would need to save two versions of the filename but, by default, GF only allows one value for this field.
Hello,
I’m creating a custom PDF template, but when I export uploaded files, what appears in PDF is the path of the uploaded files. Is it possible just exporte the filename? example.pdf
Thanks
Hi Carla, I’d ping GF support. This snippet just handles renaming the files.
Greetings!
I want to ask if this snippet can sanitize the NON-English characters in the image title.
I have made this code as a plugin that works fine, but only in posts (it rename the post link from greek character to latin characters)
Is it possible to integrate this code to this excellent snipet?
Thank you!
there is no sanitize for not latin characters
all non latin characters is translated to letter y
how can this fix?
We don’t have a fix on hand but I’d be happy to add this as a support request if you’re a Gravity Perks users: http://gravityperks.com
Hello! And how to add a field name to thHello! And how to add a field name to the file name?e file name?
Hello. If the form has several different fields for uploading files, do you need a separate code for each of them?
I have this snippet working in a custom plugin on one of my test sites – current hosted on GoDaddy. Works great and able to rename multiple files that are part of my form. Now implementing the same plugin/form on another host – Flywheel – and while the files save as part of the form process, the snippet renaming doesn’t work.
Is there something I need to check on my Flywheel host that might be keeping this snippet from working?
I’m getting an error when trying to insert this snippet into my functions file. I’m using GF 2.2.5, WP 4.9.2, PHP 7.
Does the snippet need to be edited to work with this setup?
Forgot to check “notify on followup comments” :-)
Here’s a good place to start: https://gravitywiz.com/documentation/snippet-troubleshooting/
Will this work with Gravity Forms v2.3 RC2 Released? Thanks!
We have so many snippets we aren’t able to test them all with new versions of Gravity Forms ourselves. If you find there is something not working, please let us know. :)
Thanks, only the new version introduces a totally a major change to the database schema so as this snippet is a must-have for us it really needs to work.
I have 5 potential files that can be uploaded to my form, and I need to prepend the filenames of each with the values from 2 other fields in the form. Possible?
It sounds like you’re trying to do something like the “First and Last Name” example in the article. Take a look and let me know.
Correct. I have the code working for a single file. How do I get it working for multiple?
No need to respond. I was able to get my multiple file renaming working. Thanks – very useful snippet.
Is it possible to include a folder that the file(s) should be uploaded to? So I could save the files to:
/CustomerName/uploadedfiles.txt
I am currently doing this with another file uploader plugin and would like to replicate the same setup… Thanks! Mel
Yes, just include the folder name in the “template” parameter.
Does this work with the Dropbox addon? Like can we use this to make sure the file gets renamed to include the submitter’s name?
We use this script with the Dropbox addon and it works great.
Trying to put this in my functions.php and I have one question and one problem.
Question: My functions.php file is getting pretty long… How would you recommend I go about putting this in it’s own PHP file and calling it from functions.php? I know that might be a basics question, but I’m still learning :-)
Problem: When I do put this in my functions.php, I get an error that it can’t be saved. It says “The document could not be saved. Text encoding Western (ISO Latin 1) isn’t applicable.”
Hi Kari, hm, not sure about the error you’re getting. You can use require() to require other PHP files via your functions.php.
Great snippet, thanks!
I’m trying to prepend an incremental counter to each filename–basically ‘serialize’ each uploaded file, example: AW000001-{filename}.jpg, AW000002-{filename}.jpg, AW000003-{filename}.jpg, …
So for each upload (multiple forms, multiple upload fields), the number should increment up by 1. This would allow for easy sequencing and finding files after upload. Using Woocommerce and Gravity forms addon to accomplish this. Uploads are for custom art to be added to products.
Any help would be awesome, thanks!
Hi Brian, this would be a great combo with Gravity Forms Unique ID. GF Unique ID would handle generating the sequential, prefixed number. This script would handle renaming the file.
Interesting. Thanks for the quick reply. I see that the unique ID is “unique to the form and field”. So with 2 upload fields in one form, would one Unique ID field be used to rename both files uploaded? Or would there/should there be 2 unique ID fields in the form? Thanks again!
Hi everyone,
I believe I found an issue with this code, I’ve been trying to debug an issue where some users are not getting their notifications, we found a pattern on Friday, it seems to be all users who upload files, user notification does not trigger and admin notification is not sending from configured email properly. It sends from a default email address instead of the logged in users email.
Any insight from in resolving this would be very helpful!
Never mind, I should have tested removing the code before I put this comment up, I will blame it on lack of sleep :)
Great snippet and I come to GW and recommend it to everyone who uses GF!!!
Ken
David,
Another very helpful bit of code! One wrinkle: for my use case, cleaning with sanitize_title_with_dashes() wasn’t quite perfect, as it was clobbering case in the value of the selected merge tag. To get around this, I just added a new “uppercase” argument, default false, that would apply strtoupper() before returning from clean(). Since mixed case doesn’t matter for me here, this worked out just right.
I published my changes here:
https://gist.github.com/FPCSJames/6a4a6c2882d7c7ee4fc3fe6087d85193
Cheers!
Awesome! Glad to see folks being able to extend this for their own use-cases. :)
This script is great and saves us a lot of work renaming files manually. One question will it work from mobile devices. It works great with computer broswer but when I try on mobile device the file does not rename. Any ideas please? Thanks :)
I just tested from my iPhone without issue. Not sure what would be causing this but, if you’re a Gravity Perks users, we’ll be happy to dig into your specific use-case via support.
Thanks I will do some more testing first. So far I can confirm the issue happens with Android. But maybe there is some sort of conflict with a plug in or maybe a conflict with the plug in “Gravity Forms – Uploads as Attachments”??
I don’t see why it would have issues on any mobile or other device. The code is server side and there is nothing I’m aware of that checks for what device or browser you are using unless it’s being done by GF itself. I’ve been through the code dozens of times and never seen anything that would cause this. Do you have any other GF modifications?
I disabled some plugins and did some tests and it still doesnt work on Apple or Android only via the browser. It must be something on our site that’s causing it I suspect. Ill keep digging and testing. Glad to know that the issue is on my end though because at least I know I can fix it.
Hi – this works great!
One question – is there a way to generate 2 notification emails (one with renamed attachments and one with original file names?
The original file names are not preserved. You would need additional custom functionality to make this work.
Awesome snippet. Really what I needed for my application!! Wondering how to use it on multiple forms? I tried adding two new GW_Rename_Uploaded_Files but that didnt work.. Any help greatly appreciated cheers :)
I need both forms 9 and 13 to rename to map
That should work. Here’s more details to make sure you were doing it correctly. :)
https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
Hi GV, I’m using the snippet and use a single unique code in every entry, for example: ‘LQ23XWU812’. I want this to be first in the filename (e.g. LQ23XWU812_test.pdf).
But what I get is lq23xwu812_test.pdf.
Is there a way to keep the uppercase for the letters? Thanks for your help!!
Hey Erik, pretty sure this is happening in the clean() method. You can overwrite this method with your own like so: http://snippi.com/s/drwp4vh Note that you would now instantiate an instance of your custom class (which extends the base class) when initializing this functionality. Let me know if you have any questions. :)
Works like a charm! Thank you very much.
Hi Dave/Erik,
I am working on the same issue, can either of you explain a little more about what info would need to go in the array() (last line of the snippet) of the new class which extends GW_Rename_Uploaded_Files.
Hi Dave/Erik,
I am working on the same issue, can either of you explain a little more about what info would need to go in the array() (last line of the snippet) of the new class which extends GW_Rename_Uploaded_Files.
I am trying to take it one step further, I would like Mixed Capitalization (so Ken-File-Uploaded.jpg).
Thanks!
Ken
Hi David
Would this code work if I am saving uploaded images to Dropbox via the official add-on?
Hi Charl, it has not been tested with the Dropbox add-on. Let me know if you run into any issues.
Hi David
Thanks again for this great resource!
I have installed the snipped, but then active the upload is saved without any name, just the file extension.
I have tested the code on 2 sites with te same results.
The good news is that it does work with DropBox… :-) but then DropBox is enabled it also saves the file without the name.
Thanks again for your help!
Hey Charl, I’m not able to recreate this issue on my end. Can you share how you’ve configured the snippet?
Hi David
Not sure if I understand you correctly…
I added the code to site making use of the Code Snippets Plugin by Shea Bunge.
Then the code is set as active the upload is successful in WP and DropBox but without any name.
I can provide you with admin access if needed. I believe if we can get the WordPress upload to work the DropBox upload will be correct as well.
I paste the code below… from the test site.
Thanks
Really excited to use this piece of code.
I have a field called Reference Code which will store data like “REF CODE 007-A”
Is it possible to trim this down to REFCODE007-A and then prepend this to file names?
I know I can do this with hooks e.g. https://www.gravityhelp.com/documentation/article/gform_save_field_value/ but wonder if I can then use that in the file names.
I would add a Hidden field to your form and copy the value from your Reference Code field via the gform_save_field_value filter to the Hidden field with any formatting changes you would like to see. Then use the Hidden field merge tag in the rename template.
Have you tried this?
Fantastic piece of code. This is very helpful. Thank you for sharing!
Glad to help, Aaron. :)
I’m having the same issue. Snippet works fine on its own but when I change the path the it doesn’t work
You can actually set the path in the template so long as it’s in the root is the uploads folder. If you’d like us to take a look at your specific filter usage, pick up a copy of Gravity Perks and drop us a line via support.
Hi,
Is it possible to use this snippet if I have changed the path of the file upload using the gform_upload_path hook?
Thanks
Yep!
Cool! Any tips on what I need to change in the snippet to get it to work please?
It will just work. If you’re having issues, make sure you’re return the correct value via the gform_upload_path filter.
Oh it doesn’t work for me. My file is going to the new folder but the filename isn’t changing to what I have set in the code. All it does is adds a number to the filename if there are two files with the same name.
What do you mean by making sure I am returning the correct value via the gform_upload_path filter?
Thanks
Hey David!
I’m about to put this fabulous snippet into place. (yet another thank you to you!) I have 3 forms, each with a few upload fields. (the forms started as one and were duplicated so several field numbers are the same, in case this looks confusing)
My forms and their fields are:
Form 16: Upload fields: 47, 49, 50, 52, 167, 169 Form 18: Upload fields: 47, 49, 50, 52, 167 Form 19: Upload fields: 47, 49, 50, 52
I’m following along with the tutorial you put here: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
My question is this: I’m only guessing at the best way to do this, but my thinking is that it’s better coding if I set this up to run through all the different fields within, say, form 18 then move onto the next form and its fields rather than (1) form 18, field 47 (2) form 19, field 47 (3) form 18, field 49 (4) form 19, field 49… etc..
Or would it matter at all either way?
Thanks! Mische
One more question here too. I’d like to tack on the field name to each one of these so users can tell what it is at a glance. Not sure what the field label merge tag looks like or if it would work so I want going to try a literal statement in the string.
Would this work?
Hi David, thanks for the fast reply that helped lot. Looking forward to the plugin version just to get the configuration done more elegantly instead of working in a config file… One further question: what does “1.3” stands for in the example “{Name (First):1.3}? Best, Martin
Hi, how can I use the snippet when having some dozens of forms? And: will it work also when multiple images are uploaded via one image field?
Best, Martin
Hi Martin, here’s a crash course on your first question. This will be a plugin soon but no definite ETA.
https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
And yes, this supports multi-file upload fields.
This is working well for me, using on two different forms, with different field IDs.
Thanks for the affirmation, Brian. :)
How would we set this up for more than one upload field? Ie: i want people to upload 5 images, using 5 different upload fields, then i want to make sure i add something to each of the file names (ie: A, B, C, D, E). I’m assuming within the ‘new GW_Rename_Uploaded_Files’ array I’d add another array and change the field iD? Just not sure how that would be coded…
Hi Aaron, this will help: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
Not working with WP Multi-site.
Do I have to change anything?
Thanks
Hi KA, I just tested with multisite and this is working for me. Are you using any other custom code to modify your file uploads? Can you share your configuration?
Hi David, is there a way to use multiple merge tags in the same from?
Besides renaming the image file, I would like to auto-fill the ‘alt text’ and ‘caption’ of the image uploaded via the Post Image field.
Hi there,
Any updates for the renaming portion to get it work? Using Snippnet 1.4 and latest version of GF of 2.1.1 is not working for me. If yours is working fine, can you advise your settings and code to us, so that we can test it out.
Appreciated.
Thanks. Jo
Also not working for me with the latest 1.4 snippet.
Hi David. Yes. After some fiddling around I’m getting this kind of result:
/index.php?gf-download=2016%2F11%2F10586-john-smith.mp3&form-id=6&field-id=2&hash=5f09ebcc10c45c941029e51a6f75c5dac36ee8d8074d64b78c81a83bdd663ff9
when using: {embed_post:ID}-{user:user_firstname}-{user:user_lastname}
I was slightly hoping it’d be a little cleaner, returning something like:
/john-smith.mp3
Have I missed a step? Thanks!
Hi there,
I try using the latest version and it is not working too. I have paste the code again in my functions.php in theme folder and it is just not working. Anybody has the same issues?
Are you using GF 2.0.7.15 or greater?
Yes. I am using 2.1.1 the latest version and it is not working. Anyway to test it, as I am running an important event now and i will have problems if it is not resolve asap. Currently, I am manually renaming the files. Please help if possible.
Thanks.
i can also confirm that this is no longer working on GF Version 2.1.1
Are you using version 1.4 of this snippet?
thanks for the quick response. yes, latest version of gravityforms and latest snippet (just copied the latest version today and tested both locally and online) I had another hook which moved the upload location which i thought may be interfering but when i removed that it still didn’t work. files are uploaded successfully but no renaming occurs. I tried a static filename also just to be sure it wasn’t an error with the merge tags. are you able to reproduce?
i am slightly closer to getting this to work, the first issue is that i noticed that is_callable(array( ‘GFFormsModel’, ‘get_phsyical_file_path’) returns false so the code halts before it even gets a chance to do anything. this is because there is a typo on in the method name (s and y the wrong way around)
ive addressed this and wrapped the GFFormsModel::get_physical_file_path in a function in case it is prone to change (it was in a number of places in your class)
unfortunately it still doesn’t rename the files as expected but that should make it a bit easier to troubleshoot. my next step will be to look for any more typos, as i had presumed the code provided above had been tested
Hi Ben, thanks for pointing out the typo. I was actually the person who committed that new method (get_physical_path) to Gravity Forms and I committed it there with the typo as well. Everything was working for a bit because the typo was in GF and the snippet. One of my GF coworkers must of fixed the typo there causing the snippet to break again. I’ve updated the typo here and confirmed that everything is working.
I also tried with the gform_upload_path and this worked without issue for me. Here’s the exact code I used (code).
i can confirm its working now with the typos ammended. i am facing a separate issue now which is that the gform_upload_path_XX filter no longer works (it does work but it negates the file renaming) i assume this is because of the order the hooks.filters are firing. When i try to use your code in conjunction with the upload path filter the files are moved to the correct destination but they keep their original file names. not sure what the workaround for this is as i cant find any ref to the order in which the GF filters and hooks fire
Hey David – I have a similar question as the person in this last comment. I’d like to take the Last & First names of the person filling out the form (any of the forms on our site) and have a folder created where the files will land. (in my case it’ll be a bucket on S3)
Please forgive me if it’s in poor taste to link to someone else’s code but I just found this: https://gravitywp.com/tutorial/custom-upload-path-gravity-forms/ I tried hard to find your renaming snippet the person above is talking about but couldn’t locate it.
Any chance you can pass on a handy little snippet that would do this? Grab info from a certain field or merge tag, go to ‘some-user-defined-spot’ and make a folder there?
Seriously, if you have something like this kicking around, you’ll be my hero forever.
Hey David
Thanks again for another great snippet.
Just wondering if you have any idea on how to change the upload path as well.
I’ve tried this snippet of yours that I found but it doesn’t seem to work with the file renaming snippet:
add_filter( ‘gform_upload_path’, ‘change_upload_path’, 10, 2 ); function change_upload_path( $path_info, $form_id ) { $path_info[‘path’] = ‘/home/public_html/yourdomainfolder/new/path/’; $path_info[‘url’] = ‘http://yourdomainhere.com/new/path/’; return $path_info; }
Do you have any ideas?
Hi David, it’s me again, this time I have a problem: I’ve installed the latest version of GF 2.1.0.1 and downloaded your raw code version 1.4, but the renaming doesn’t seem to work. Here is what I uploaded a file named “02logo(1).stl” and click download file button in the gravityview custom content: “wp-content-uploads-gravity_forms-1-7e38ba7731a19dd489bc64977595aeff-2016-11-02logo1.stl” It’s quite a long name, and it’s supposed to be like “ff3dm-02logo(1).stl”, because the template is: ‘template’ => ‘ff3dm-{filename}’ So I’m confused why it’s not working, I have added another snippet “Customizing the Multi-File Merge Tag”, does that affect the output result? Thanks!
Hi,
I also installed GF 2.1.0.1 and the renaming does not work anymore. It was working well with GF 2.0.7.15, so GF has changed something that breaks the code… :( Hope David you have an idea on how to resolve this, your code is so useful! :) Thanks,
Hey Matt, deleting this comment since I responded to your comment above. Sorry for the slow response. We had to prioritize some urgent Gravity Perks issues last week.
@Sean P Sullivan
Yes, i have the same exact problem than you with 2.0.7 of gravity form, the file renaming is not working anymore. I’ve compared your code proposed with the one I have and they are the exact same code… @David, any idea how we can make this code work with latest version of GF? Thanks for your help.
Hi Quentin, install Gravity Forms 2.0.7.15 or greater and the latest version of the snippet above (1.4). Let me know if your issue persists.
Somethings not working.
[code removed; please use snippi for code examples]
This code always seems to go true on the check for GFFormsModel being uncallable. Not sure why. Running lates GF. Weird thing is I’ve seen it work one out of 25 times. :(
Not sure if it’s a bug in the latest GF version or not.
Yup. Something to do with 2.0.7 and your newer code. I’m using this code (which does not match what is in your links on this page now). It works. The code you have listed does not work with 2.0.6.5 or 2.0.7.
[code removed; please link code examples over 5 lines]
Hi Sean, you’ll need to update to Gravity Forms 2.0.7.15 to run the latest code. It is available here.
Hi Sean,
I also found this script to break on v2.0.7. I left a comment here a few days ago, but it was deleted.
Out of interest – how does your new code differ to the old? I’ve scanned it but cannot spot the change you made.
Cheers,
Matt
Hi Matt, install Gravity Forms 2.0.7.15 or greater and the latest version of the snippet above (1.4). Let me know if your issue persists.
This code is not working on forms created with the latest version of Gravity Forms (2.0.7). I’ve tried it on multiple private sites and it does not rename the file. On forms that were created with previous versions it does work however (2.0.3.5).
Hi Robert, just a friendly acknowledgement that your comment here was not lost in the void. Glad I was able to help you via RG support. :)
Added the snippet to functions.php, changed the variables under #Configuration, and… nothing. Files are not renamed. Looking through the GF log (GF Plugin Logging Addon), I don’t see any attempt to rename. (Not sure if it should show up there.)
I’m using merge tags, but also tried with just text appended, and that didn’t work either.
I’m using custom upload path script as well, and tried removing that as well.
Here’s the configuration code for this page: http://georgiawatercolorsociety.com/national-exhibition-form/
new GW_Rename_Uploaded_Files( array( ‘form_id’ => 2, ‘field_id’ => 38, ‘template’ => ‘{Name (Last):1.6}-{Name (First):1.3}-{Title:7}-{filename}’ ) ); new GW_Rename_Uploaded_Files( array( ‘form_id’ => 2, ‘field_id’ => 39, ‘template’ => ‘{Name (Last):1.6}-{Name (First):1.3}-{Title:16}-{filename}’ ) ); new GW_Rename_Uploaded_Files( array( ‘form_id’ => 2, ‘field_id’ => 78, ‘template’ => ‘{Name (Last):1.6}-{Name (First):1.3}-{Title:24}-{filename}’ ) );
Have I missed something obvious? Thanks!
Hi Diana, install Gravity Forms 2.0.7.15 or greater and the latest version of the snippet above (1.4). Let me know if your issue persists.
Hello David,
We are currently only able to access a forms uploaded images after the form entry has been exported to CSV.
Within the WP admin area, when trying to view the image uploads within each entry, its as if the correct file path hasn’t been written yet. When we try to view the upload it says “image not found”.
Do you have any idea what might ve wrong?
Kind regards,
Jonathan
I’m not sure if this is related to all the GF 2.0.7 issues but that’s a good place to start. Install Gravity Forms 2.0.7.15 or greater and the latest version of the snippet above (1.4). Let me know if your issue persists.
Hi David, I found your script great, but I have some weird problem.
Sometimes the script rename the files correctly, and sometime it doesn’t.
This is the code I used:
Configuration
new GW_Rename_Uploaded_Files( array( ‘form_id’ => 2, ‘field_id’ => 6, ‘template’ => ‘{Nome del gatto:3}-di-{Il tuo nome:1}-1’ ) ); new GW_Rename_Uploaded_Files( array( ‘form_id’ => 2, ‘field_id’ => 7, ‘template’ => ‘{Nome del gatto:3}-di-{Il tuo nome:1}-2’ ) ); new GW_Rename_Uploaded_Files( array( ‘form_id’ => 2, ‘field_id’ => 8, ‘template’ => ‘{Nome del gatto:3}-di-{Il tuo nome:1}-3’ ) );
Do you have any idea?
Thank you!
Can you show me some examples of the originally uploaded filenames and what they were renamed to when it fails?
I don’t know when it happens, ’cause it is a public form, where people upload their images.
There is a list of the latest uploaded files: 20160827_193354.jpg Brinotto-di-Anna-3.jpg Brinotto-di-Anna-2.jpg Brinotto-di-Anna-1.jpg IMG-20160630-WA0000.jpg IMG-20160914-WA0001.jpg 10888803_875536422497426_7774155400995582800_n.jpg 20160809_0736000.jpg 20160805_103636.jpg 20160731_200337.jpg
It seems it totally skip the rename phase :|
I’m having a similar issue in that the renaming is not always occurring when the file is uploaded. Seems that the renaming does not take place anymore, except for sporadic occasions where it does work.
The original filename is maintained unaltered.
We also have this process linked to a Dropbox upload into a shared folder.
Try installing Gravity Forms 2.0.7.15 or greater and the latest version of the snippet above (1.4). Let me know if your issue persists.
We’re having an issue where our users are managing to upload empty PDF files. After looking in the gravity forms logs it appears users are getting to page 2 of a 3 page form, uploading the file, than coming back several hours later to submit it. We’re using this script to rename the uploaded PDF file. I was wondering if your script could be causing these empty PDF files. I’m assuming the file in the temp directory is gone by the time the user comes back and your script could be creating a blank file with the new name in the downloads folder.
The website is an intranet which requires a google login from the companies domain so it’s not easy to share the page with you.
It seems unlikely. This code is not run until the final submission is being processed. Best way to test is to figure out the exact steps to recreate and then remove the code and see if you can still recreate the issue.
I’m trying to rename uploaded files but having issue with special characters. For example:
Visitor would use form to upload their image title, first and last name, and a category so that the image name would end up being:
Category[Firstname_Lastname]Image_Title.jpg
But I’m getting:
CategoryFirstname-LastnameImage-Title.jpg
It’s stripping the “[” and “]” characters and using dash instead of underscore to replace spaces in image title.
How can I fix this in the code? The format is very important as the images are ran through another program that requires this format.
Hi Sean, the filename is “cleaned” by the
clean()
method. Here’s an example of how you can extend this class and override the default clean() method with your own.https://gist.github.com/spivurno/eea345cbe4bf5d9e691330db9242f5d4
Little confused as to what “clean” function you are referring to. I don’t see that function anywhere in GF or in WP. Not a strong WP coder so little confused as to what I should code to override in that function.
I’ve been through all the code for GF and find NO clean() method.
Finally gave up. Tried creating an plugin but the WP version of the sanitize_file_name() method seems to be called first time and I can’t seem to change that. Tried overriding it with a new add_filter in functions.php. No good. Created a plugin that is first in the list (before GF loads) and still no go. I had to resort to simply removing the [ and ] characters from the formatting.php file and make the file immutable (to keep WP from overwriting it for now). Time to move on to other things and come back to this later.
greetings from greece!
great snippet! when renaming, can you please tell me how to add in template one of the fields of the form? it will be very, very usefull!
thank you for your support and for your help!
Glad you like the snippet. I believe you’re looking for the “First and Last Name” example above.
Works great, thank you so much!
Glad to help, Justinas. :)
Thanks for the great work. I’m creating an upload portal for students to upload their home work. I want to have the file be uploaded to a folder with the user’s name. How would I go about doing this?
I don’t have a ready solution for this but this might help get you started: http://wordpress.stackexchange.com/questions/174371/gravity-forms-upload-each-entry-to-unique-folders
Will do. Thanks David.
The folks at gravity forms helped with this one. Here’s what worked.
add_filter( ‘gform_dropbox_folder_path_(insert form # here)’, ‘change_path’, 10, 5 ); function change_path( $folder_path, $form, $field_id, $entry, $feed ) {
}
I’m trying to rename uploaded files as the post ID from the post created in the form. I tried using template => ‘{post_id}’ but it didn’t work. Why?
Hi Fliint, this code renames the files on the pre submission filter. The post has not been created at this point yet so the post ID is not available. We may add support for this in a future version.
Hi David,
Thanks for this code – works great, just what I was after. Would also like the code to rename a file when it is added to an entry (on the same form) via admin’s edit entry detail screen, it currently doesn’t. Any help on how to accomplish tha would be great.
Thanks.
Hi Vicktor, this makes sense. I’ve added it to the roadmap for this snippet. Currently, it’s not a simple thing to explain how to accomplish since the form submission process in the admin is completely different than the frontend.
This is handy! Is there a way to use merge tags to auto-fill the ‘alt text’ of the field as well?
Are you using a File Upload field or a Post Image field?
David, I’m using the Post Image field.
What if I want to rename to post title while I am using Gravity for guest submit post?
Your example for this form was for complex forms…
I’m not sure I understand? Could you elaborate?
Hi.
What if the field name was in arabic ? Can I only use field ID and Name for renaming??
Regards, Vahid.
This method is not working with UTF-8 characters like Arabic/persian..
So please check and let me know.
{pagetitle:2} is only working for English chars.
Regards, Vahid.
Your snippet in not compatible with RTL languages like Persian,Hebraw,Arabic. So please use UTF8 instead of ANSI or unicode for renaming.
I was able to rename to English chars,but couldn’t do same with Persian chars.
Regards, Vahid.
Hi Vahid, if there is more demand for this moving forward, I’ll definitely looking into adding support for this.
[…] So all the user needs to do is add their name and attach the file. There’s also a Gravity Forms hook that renames the file so that all the relevant information is there when it’s […]
Hi!
Your snippet work very good, but i have one problem: Sometimes when i rename files on: {Name (First):1.3}-{Name (Last):1.6}, I have “special characters” like: à or è, ò… After rename file on server i have problem to use/download this files. Can you add script to rename special caracters when i rename file name? From special caracters to normal caracters?
Thank you for help!
Nick
Works well. Thanks. Would this work for several forms on the same site? They would have different form ids so could we just change the line ‘form_id’ => 628,630,631
Hi Kevin, this might help: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
Thanks. What if we wanted to have the files in a different path location? I found a filter that allows this but the email upload doesn’t work now.
Thanks for this snippet. It works nicely but I ran into a small issue. I am trying to add fields (to the filename) which are ‘filled’ dynamically; 1 from an Advanced Custom Field, 1 from the slug.
The dynamic fields are listed in the confirmation email but the file name does not get changed.
The dynamic filling of the fields happens in gform_pre_submission. Could it be that gform_pre_submission is run after this snippet ?
Or do you know a solution to get dynamically filled fields into the filename as well ?
PS it happens in gform_pre_submission_2, not gform_pre_submission
Hi,
I’m using your code since several month and it works really great :) I have a question as I would like to change how the images are renamed when we have multiple files. Now, with this code the file are renamed like this: file1 file2 … In my case, I want to achieve a little modification by adding ‘-‘ between the filename and the number, so it will look like this: file-1 file-2 … Is this possible? I really don’t see where to modify the code to add this ‘-‘? Thanks a lot,
I want to do a static rename, but leave the file extension. For example, I might upload a file called WordPress-2016-PHP-Resume-David-Smith.docx, but then save the file as Resume-David-Smith-2016-01-15.docx. I haven’t seen any merge tags that allow such a date format or that show the current file extension. How would I accomplish this with your code?
Thanks for any help.
mts7
I ended up doing this to enable my own custom merge tags.
// inside get_template_value $template = str_replace( array(‘{filename}’, ‘{ext}’, ‘{date-ymd}’), array($filename, pathinfo($filename, PATHINFO_EXTENSION), date(‘Y-m-d’)), $template );
// call to class array element ‘template’ => ‘Resume-{Name (Last):3.6}-{Name (First):3.3}-{date-ymd}.{ext}’
I know it’s not elegant, but it gets the job done. I’m not too interested in extending your class at this time. Thanks for your code!
You can use PHP in the template name when you define it. Example:
'template' => '{filename}-' . date( 'Y-m-d' )
This would not strip the 2016 from the middle of the filename per your example but it will append the date to the end of the filename.
Would it be possible to add the page title to the file name?!?
It would. Something like this could work:
'template' => is_page() ? get_queried_object()->post_title : 'static-file-name'
Hi I’m using GF data to be uploaded to a database. I want to rename my files as the IDs of the data entries. E.g. latest ID was 1234 so I want my upload to be 1234.pdf
I’ve been trying to use ‘template’ => $wpdb->insert_id but it isn’t working.
Thanks in advance :) Asher
Hi Asher, this runs before the entry has been created so currently there is no way include the entry ID. If you’d like to commission me to find a solution for this need, get in touch.
Well the database entry query actually runs before the code you’ve provided. I don’t see how it wouldn’t work.
Is it possible to add a hidden field, which is generated by conditonal logic, in the rename option ???
I add a hidden field, which is generated from an Advanced Custom Field, with this function:http://pastebin.com/QqjVikDH
I then add it like this: http://pastebin.com/em8pnRt5 but I never get the field {Vacature ID:8}. Is this also ‘filled’ after save/submit ? Like entry_id is (without hacking it…)
You’ll want to change just one bit:
add_filter( 'gform_pre_submission_4', 'load_vacature_id', 9 );
The “9” will make sure this runs before the renaming snippet.
thanks, i had achieved it myself in the meanwhile.
Thank you so much, do you know how can I remove special character like á é í ó ú ñ from the filename?
Hm, give this updated version a try: http://pastie.org/private/hvjsrpfwtuyii9zimmjg If it works for you, I’ll update the article as well. :)
don’t special characters get replaced with ascii notations ? I tried using a replace string with a quote and a space in it and it was no prob. the chars were replaced by an accepted notation.
Just another little question to improve the code, how to remove all the special character (sanitize) the name? For example I received two post: One with a ‘ in the title and the ‘ was changed to 039 One with ” in the title and the ” was changed to quot
Is there a way in your code to sanitize the post title before changing the name of the image? Thanks :)
Here’s an updated version: http://pastie.org/private/hlxgse6toptwxr4y7gp2w Can you take it for a spin and let me know how it works for you? If it works well, I’ll update the article with the new code.
Hello,
I’m searching the exact same function for post images fields but after searching for hours couldn’t find a solution to it. I’ve contacted GravityForm and they don’t know also and point me again to your post. I’ve tried the plugin File Renaming on upload but it does not work and this plugin has not been updated since two years so should be near end of life. I’ve tried your code but does not work with Post images, so my question is do you know what should be modified in your code to make it work with Post Images fields? You are my last chance :) Thanks a lot!
Gravity Forms v1.9.15 adds support for a new gform_media_upload_path filter that will allow you to modify the path for Post Image fields.
Thanks David! It works perfectly…I’ve spent so many hours trying to do it…thanks a lot! :)
My pleasure! :)
Hello,
How can we make this snippet work with Post Image field?
Thank you.
Support for Post Image fields was just added. Enjoy! :)
Incredible tip! Thanks a lot!
Glad you found this useful. :)
If you have several uploads in a form. How do you set up the code? Like:
‘form_id’ => 12, ‘field_id’ => 2,3,4,6,8,12,34 ‘template’ => ‘{user:id}’
This article will help:
https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
It says “different” forms, but the same concept applies to applying a snippet multiple times to the same form.
Thank you! That worked great!
Glad to help!
This looks like what I need. Will this work for renaming the uploaded filename field based on merged field values prior to the filename being upload to Dropbox? I have total of 4 File Upload fields that load the files into Dropbox.
Hm, I actually don’t know. This was developed before the Dropbox Add-on and I haven’t tested this with it. If you do, could you report back your results?
I get ‘{Name (First):1.3}-{Name (Last):1.6}-{filename}’ to work, but I can’t get ‘{entry_id}-{filename}’ to work. Any tips?
Hi Andy, does it replace either merge tag when you use ‘{entry_id}-{filename}’?
I’m not sure I understand your question, but when I use ‘{entry_id}-{filename}’ the file is not renamed, it just keeps the name it had originally. I have also set in a hidden field in the form grabbing the entry-id so I can see it when exporting.
My functions ends like this:
Configuration
new GW_Rename_Uploaded_Files( array( ‘form_id’ => 1, ‘field_id’ => 3, ‘template’ => ‘{entry_id}-{filename}’ // most merge tags are supported, original file extension is preserved ) );
Hi David! Just want you to know that I’ve been in contact with Gravity forms and they say it is impossible. The entry_id is not known until after the entry is saved. So I have to find another way to link the uploaded image to the entry.. Thanks anyway!!
i’s possible : add this, it change the name, update the entrie in the DB, and move the fil where you whant
[code removed]
Hi wedz, thanks for sharing your solution! The comment processor butchered your code and it was causing issues with the rest of the page. Could you share your code via a pastie URL instead?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
<?php
add_filter(“gform_upload_path”, “custom_upload_path”, 10, 2); //this is a gf filter which changes the upload path function custom_upload_path($path_info, $form_id){ if($form_id==2){
} /* add_filter(“gform_pre_send_email”, “before_email”); function before_email($email){ $email[“abort_email”] = true;*/
add_action(“gform_after_submission_2”, “custom_after_submission_2”, 10, 2); //this is a gf filter which lets us get an entry after it is done. we will use this to automatically rename files (only form 2 in the example) function custom_after_submission_2($entry, $form){ foreach($form[‘fields’] as $key => $field){ //this will get all the fields that are a fileupload type if($field[‘type’] == ‘fileupload’) $keys[] = $field[‘id’]; } foreach($keys as $value){ //this will save the url info for all the fields which were submitted $pathinfo = pathinfo($entry[$value]); if(!empty($pathinfo[‘extension’])){ $oldurls[$value] = $pathinfo; $pathinfo[‘filename’] = $entry[‘id’] . ‘‘ . $entry[‘26.6’] . ‘‘ . $entry[‘26.3’]; //we are going to make the files look something like this entryid_formid_fieldid… so you may have something like 323_9_12 for the filename. this system ensures all filenames are unique and sorted. you can make the name anything you like. remember it is the filename only (no path and no extension) $newurls[$value] = $pathinfo; } }
}
sorry
http://pastie.org/10583931
Hi!
I use snippet for Rename uploaded files, and all work Ok. Now i cange filed to Multi-File Upload, and i see on database that i have ” backslash” on my link.
Example: http://mysite.com/uploads/2015/09/10/test-Foto1.jpg – link for normal uploaded files
When i use Multi-File Upload i have:
[\\http://mysite.com\/uploads\/2015/09/10\/test-Foto1.jpg%5D
Can you tell me how delete square bracket and backslash?
\\share\directory\filename.ext.
Thank you!
Nick
Where are you using the multi-file field merge tag? This will largely dictate the format. The issue is that by default, it is provided as a JSON encoded string of the files names. This is where the square brackets are coming from.
I would like to use this on a post-image upload field, but the snipper only works on a file upload field? How can I change this to use on the post-image field as well?
Hi Andre, might be easier to use a plugin like this one to handle renaming Post Image files.
WordPress just gives me a white screen if I copy it into my themes functions.php file :-(
Hi Marcus, this might help: https://gravitywiz.com/documentation/snippet-troubleshooting/
Hello, the snippet is working well!
However I have a small issue. If anybody uses a forward slash ( / ) in a ‘single line text field’ the renamer truncates the name stopping at the slash.
EXAMPLE:
‘Gordon/Langley’ becomes ‘Langley’ ‘Gordon/Langley/v2’ becomes ‘v2’
Is there anyway of ignoring the forward slash?
Anybody?
Hello, could somebody look at this please?
Hey Gordon, thanks for your patience. We’ve added support for stripping all slashes from the filename before the file is renamed.
David – that’s great news!! When you say you’ve added support… what exactly do U need to update? Many thanks, Gordon
Hey David – I finally added you new code – works great, thanks so much!! I edited it slightly so the forward slash ( / ) is not just deleted but replaced with a dash ( – ).
function remove_slashes( $value ) { return stripslashes( str_replace( ‘/’, ‘-‘, $value ) );
Thanks a million!!
Glad to help, Gordon!
Hi, thank you for your great snippet, it really works wonders, I just have one question though, if I were trying to apply a different renaming profile, how would I do that without having the functions conflicting with each other?
Any help will be greatly appreciated.
Hi Terrence, I think this will help you: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
Hi
Many thanks for this code i was pointed here from GF Support, this is renaming the file with my desired template style, but i need to access the new file name from with in gform_after_submission hook, is this possible, i have managed to work out to some extent but i am only received the original file name not the updated one?
Many thanks in advance
Jamie :)
The file is renamed prior to submission (via the gform_pre_submission hook). The $entry passed to the gform_after_submission hook should have the renamed file. Could you send me a [pastie](http://pastie.org] of your custom code?
Hello
I can’t figure out a ‘usage example’ that includes all the user input from my form in the file name, renaming the file completely – based on all the user data. Could you explain.
The idea is that you can use GF merge tags to generate the filename based on the submitted data. In the example above, we have a Name field so we get the first and last name merge tags to generate the file name:
{Name (First):1.3}-{Name (Last):1.6}-{filename}
. Based on this, could you elaborate on what you don’t understand? I’ll be happy to clarify further.Thanks David
I got it figured… I used this {:1}-{:7}-{:9}-{:8}-{:4}-{:5} and it gave me the results I wanted.
I have a another question though, do you know how to automatically transfer the uploaded renamed file into the media library. I’ve managed to change the path so the file goes in the upload folder byt I’m having to use the plugin ‘Add from server’ to manually process the file. Many thanks, Gordon
Hi, I’m using this snippet! thank you very much!
I would like to set the filename depending on the userID that uploads it. Would that be possible?
I get the ID using
$current_user = wp_get_current_user(); $current_user_id = $current_user->ID;
But i don’t know how to include it into the array.
Thank you!
Hi Albert, Gravity Forms supports most user meta (including the user ID) via the {user:prop} merge tag. Try:
{user:ID}
in your file name template.Thank you! perfect!
I have trouble dealing with people that upload images with the extension in capital letters. I’m trying to edit the function adding a strtolower in the file_info extension wariable, but it’s not working. Any ideas?
Thank you!!
Hi!
Snippet work, but if user not upload file, i see this mesage on file url:
http://www…../wp-admin/FAILED (Temporary file could not be copied.)
Can you tell where is problem?
Thank!
Nick
Hi Nick, I’ve just updated the snippet with a fix for this issue. You can get the latest above. :)
Perfect! I try snipped after update! Work! Thanks for help! have nice day! Nick
Awesome! Glad the updated worked for you.
[…] a neat tutorial on renaming Gravity Forms file uploads, check out this article from David at GravityWiz.com. You can use his code with the code from this tutorial to rename the […]
Hi David Smith, Thanks for this nice and helpful snippet. Its really works fine for me. But one great things to be noted that, when i edit an entry and delete older file then upload a new file, it does not rename the file. Its remain in the original file name. Please check it. However your other snippet like date population is working when edit and update an entry. Thanks again.
Hi Tarequl, you are correct. This only applies to submissions made via the front-end. If enabling this in the back-end proves a popular need, I’ll definitely consider adding support for that. In the meantime, you can manually edit the file name before uploading in the backend.
I would like to second the request for this to work from the back-end (entry editor) too. I have encountered a use case where this would be extremely helpful.
This was very helpful for a site I’m working on today.
Yet, I am having an odd issue and not sure why. When the files gets moved from the directory to the Media Library, for some reason the file name ends up being displayed like “?attachment_id=7089” rather than the actual title. You can see a screenshot of it here, and as you can see, the file title and URL show a full name, but the filename does not.
At first, I thought it was because your code did not include an explicit reference for the guid in the $attachment, however even after adding it, this value does not update in the database.
Any ideas?
Hm, I’m not sure, Adam. This snippet doesn’t move the file to the WP Media Library so there is a chance of a conflict between this snippet and whatever you’re using to do that.
[…] nifty little PHP class that I implemented to send product files to an Amazon S3 bucket. That class, this snippet from Gravity Whiz and some additional code made it possible to dynamically change a file’s name, send it to the […]
Two questions. Is this for image uploads or just file uploads? Does this strip trailing spaces. For example someone puts a space after their first name in the field.
I have problems with new images overwriting old ones with the same file names, the -1 or whatever isn’t appended.
Thanks!
Hi Deborah, this is for the File Upload field specifically but may also work with the Post Image field. It does automatically strip spaces. I just tested locally and the auto-incrementer for duplicate file names is working on my end. If you upload images with the same name via WP media uploader, does it auto-increment the name?
The problem I think comes when files are uploaded via different forms and then get dumped into the same folder as other images from other forms. They don’t get the 1 or whatever added on upload. So I end up with image.jpg getting uploaded and overwritten in the year/month directory. Since they get uploaded to a separate GF directory first during image upload or file upload, when they get moved to the general folder it causes issues.
Is this only happening when this snippet is active?
Very grateful for this one. This is also useful to help prevent file names from being guessed. For example, under certain conditions (mobile device), Gravity Forms will increment image uploads with file names such as image1.jpg, image2.jpg, image3.jpg, etc. There is no longer a risk of the customer who uploaded image49 manually modifying the file name to see image[1-48], because now I can make the file name more elaborate.
[…] Wiz posted a guide on renaming uploaded files from Gravity […]