[resolved] Randomly Generate Short URL for Images Instead of Using the File Name (4 posts)

  1. Traincrossin
    Posted 3 years ago #

    I'm trying to figure out a way change the default naming system of images in WordPress. I'm wondering if there is a way to change image URLs when they're uploading so they're randomly generated instead of using the file's actual name, so picture123.jpg would turn into a random five letter/numerical string like 12abc.jpg. I know nothing about coding or WordPress' inner workings, so I don't even know if this is possible. If it is possible to change in a php file somewhere, I was thinking the base_convert function would work nicely.

    The reason I want to do this is because the actual image's name can sometimes be long and ugly so this would shorten the URL and make it cleaner for posting on other websites.

  2. Traincrossin
    Posted 3 years ago #

    Did some more searching and came across this answer. http://stackoverflow.com/questions/12062486/how-to-auto-rename-uploaded-image-to-a-random-number-in-wordpress

    Only problem is I don't see the line of code they say to change in my media.php file.

  3. Traincrossin
    Posted 3 years ago #

    Found the line of code they were talking about under the wp-includes folder, apparently there are two different php files and I was looking in the wrong one.

    I tried changing part of the code to $destfilename = "{$dir}/{$new_file}-{$suffix}.{$ext} where $new_file used to be name like they said. Then I defined $new_file = wp_basename($rand, ".$ext"); where $rand = substr(md5(microtime()),rand(0,26),5); $rand being a function that generates a random number. Tried uploading pictures but it's still using the file name, really close to a solution.

  4. Traincrossin
    Posted 3 years ago #

    Found a solution! Check it out over here, it's just creating your own php file and saving it in your plugin folder. http://stackoverflow.com/questions/3259696/rename-files-during-upload-within-wordpress-backend

    If you'd like to change the length from 32 digits to something shorter, you just need to replace a couple lines of code. I'm sure you could do it differently, but this works for me. The # in the sbstr function is how long you'd like the string to be +1 since you're going from 0 to that number.
    $name = basename($filename, $ext);
    $chop = md5($name) . $ext;
    return substr($chop, 0, #) . $ext;

Topic Closed

This topic has been closed to new replies.

About this Topic