functions – How to overwrite image if it already exists – WordPress, Gravity form

Question

How do I make the old file replaced when the user uploads a new one?

Now the files are named a1.jpg, a2.jpg, a3.jpg. If the user uploads a.jpg, then I want to overwrite the a.jpg that already exists. This shall only apply to this folder / form.

I use ultimate member together with gravity forms and gravity view. Have a form where the owner of the role (company) can upload their own company logo. It gets the renamed to the user role and is placed in a special folder.

So far I’ve managed to do this:

  • Rename the file to the user’s role – Done
  • Put the file in a dedicated folder – Done
  • If the image already exists, overwrite it – Not done

The full code can be found here:
https://github.com/gravitywiz/snippet-library/blob/master/gravity-forms/gw-gravity-forms-rename-uploaded-files.php

The configuration in functions

# Configuration

new GW_Rename_Uploaded_Files( array(
'form_id' => 10,
'field_id' => 6,
// most merge tags are supported, original file extension is preserved
'template' => '{Role:7}',
// Ignore extension when renaming files and keep them in sequence (e.g. a.jpg, a1.png, a2.pdf etc.)
'ignore_extension' => false,
) );

To put the files in the correct folder:

add_filter( 'gform_upload_path_10', 'change_upload_path', 10, 2 );
function change_upload_path( $path_info, $form_id ) {
    $path_info['path'] = '/var/www/vhosts/example.com/httpdocs/wp-content/uploads/company_logos/';
    $path_info['url'] = 'https://example.com/wp-content/uploads/company_logos/';
    return $path_info;
}

So far everything is great. The only problem I have is that when the user uploads or changes the image, it should overwrite the old one. Now when the user uploads a new one, they are named company.jpg, company1.jpg, company2.jpg etc.

How do I make the old file replaced?

0
Masterior 2 months 2023-01-26T01:49:37-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse