I have been trying to rename my images on upload and only piece of code I found was the one that uses a 32char hash.
function make_filename_hash($filename) {
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
return md5($name) . $ext;
}
add_filter('sanitize_file_name', 'make_filename_hash', 10);
My php knowledge is very limited and I looked everywhere for an example that uses some random number being generated instead of a hash, without success. My initial idea was to get the db image id and use it as image filename on upload but I got my brain twisted in the process.
Anyway at this point I would settle for some sort of numbering system that will increase by one digit on every upload or if that is not possbile at least some random number by using a range, like rand(10000,99999).
Any help would be very appreciated thanks a lot
==========================================================
Can you read data from a custom table in functions.php and write to it. I’m trying to read a counter from a table set the image to that counter number and update the counter in the db. It doesn’t seem to work, the counter increases but the table never gets updated, and no matter what the value in the db is, the counter does not use that value, so this means it’s not reading this value either. I just want to know if there is another way to do this to rename files but with a value from my custom table. This is what I got so far. I was thinking maybe I use the wrong hook but at this point I am a bit stuck. Thanks guys.
function make_filename_counter($filename) {
$qry;
$fcnt = 0;
$sql = ("SELECT counter FROM bwbps_filenamecounter WHERE id = 1");
$cnt = mysql_query($sql);
foreach($cnt as $cnt) {
$fcnt = $cnt->counter;
}
$fcnt = $fcnt + 1;
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$sql = "UPDATE bwbps_filenamecounter SET counter = " . $fcnt . " WHERE id = 1";
$qry = mysql_query($sql);
$fcnt = 0;
return $fcnt . $ext;
}
add_filter('sanitize_file_name', 'make_filename_counter', 10);
no need to use a custom table, use an option, and the
add_attachment
hook:If you’re doing them in numerical order, you could just store them in an option and just increase that option every time you add a file.
You may check the code of the “Filenames to latin” plugin.
It converts symbols from different languages to latin letters while upload.
The source code of the plugin.