How to automatically rename file name to username value for uploaded user images in WordPress - ultimate memeber plugin

101 Views Asked by At

When using the Ultimate Member plugin on WordPress, I encountered one difficult problem for me. I need the uploaded user image in his profile to turn into a link like: http://example.com/img/%username%.png The path to %username%.png is not important (the main thing is that it does not change), but I wanted so that the user's uploaded image has a name that matches the username value. Tell me how this can be implemented, I’m new to PHP and know everything very superficially.

At the moment the link looks like: https://example.com/um-download/6287/img/6/93059f79c9?t=1694944149 The only thing I could cling to is that the letter 6 is the user id.

2

There are 2 best solutions below

0
Axel Encore On BEST ANSWER

The solution to my problem was literally the only shareware file-renaming-on-upload plan with such a functionality. In it, you can automate the renaming of files depending on {port} {username} {date} and so on. https://wordpress.org/plugins/file-renaming-on-upload/

0
Champ Camba of Ultimate Member On

You may use the following code to change the filename of a stream_photo using the Ultimate Member Form's Uploader field. This changes the filename to the current logged-in user's user_login value when you Upload with the uploader field that has a meta key second_profile_photo:

add_filter( 'um_image_upload_handler_overrides__second_profile_photo', function( $uploader_overrides ) {
if( 'stream_photo' ===  UM()->uploader()->upload_image_type) {
    $uploader_overrides['unique_filename_callback'] = function ( $dir, $filename, $ext ) {
        if ( empty( $ext ) ) {
            $image_type = wp_check_filetype( $filename );
            $ext = strtolower( trim( $image_type['ext'], ' \/.' ) );
        } else {
            $ext = strtolower( trim( $ext, ' \/.' ) );
        }
    
        if ( 'image' == UM()->uploader()->upload_type ) {
            $filename = um_user('user_login') . ".{$ext}";
        }
    
       UM()->uploader()->delete_existing_file( $filename, $ext, $dir );
    
        return $filename;
    };
}
return $uploader_overrides;

} );

This doesn't change the download URL displayed in the Profile View but this let's you generate the uploaded photo with your desired filename.

Further code explanation:

UM()->uploader()->upload_image_type checks if the current uploading file is a stream_photo.

Ultimate Member has 4 upload types: profile_photo, cover_photo, stream_photo and file. In your case, you only need the stream_photo.

This is the part that renames the filename with the current logged-in user's user_login value:

if ( 'image' == UM()->uploader()->upload_type ) {
  $filename = um_user('user_login') . ".{$ext}";
}