wordpress设置上传图片自动重命名

方法一:按时间重命名

上传文件时会以“年月日时分秒+千位毫秒整数”的格式重命名文件,如“20161023122221765.jpg”

// wordpress上传文件重命名
function git_upload_filter($file) {
	$time = date("YmdHis");
	$file['name'] = $time . "" . mt_rand(1, 100) . "." . pathinfo($file['name'], PATHINFO_EXTENSION);
	return $file;
}
add_filter('wp_handle_upload_prefilter', 'git_upload_filter');

源代码:http://www.lmlblog.com/2147.html

方法二:用MD5加密生成数字并重命名

名称规则是由系统自动生成的一个32位的MD5加密文件名,由于默认生成的32位文件名有点长,所以使用substr(md5($name), 0, 20) 截断将其设置为20位。

function rename_filename($filename) {
	$info = pathinfo($filename);
	$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
	$name = basename($filename, $ext);
	return substr(md5($name), 0, 20) . $ext;
}
add_filter('sanitize_file_name', 'rename_filename', 10);

源代码:http://www.boke8.net/wordpress-auto-rename-file.html

方法三:中文图片自动重命名

当你上传图片时,主题会检测图片名中是否包含中文字符,如果包含就执行重命名的机制,如果不包含那么直接用上传的名称作为图片名

/* 
代码功能:中文名图片上传改名
代码介绍:http://chenxingweb.com/wordpress-uploads-zh-move.html
 */
function tin_custom_upload_name($file){
    if(preg_match(‘/[一-龥]/u’,$file[‘name’])):
    $ext=ltrim(strrchr($file[‘name’],‘.’),‘.’);
    $file[‘name’]=preg_replace(‘#^www\.#’, ”, strtolower($_SERVER[‘SERVER_NAME’])).’_’.date(‘Y-m-d_H-i-s’).‘.’.$ext;
    endif;
    return $file;
}
add_filter(‘wp_handle_upload_prefilter’,’tin_custom_upload_name’,5,1);

来源:https://www.cnntt.com/archives/2946

使用方法

将代码添加到当前主题functions.php模板文件中即可。

方法四:修改源程序文件

操作方法:

在wordpress程序的wp-admin/includes/目录中找到file.php文件,并进行编辑,在327行左右找到以下代码:

// Move the file to the uploads dir
$new_file = $uploads['path'] . "/$filename";
if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) )
return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );

将其替换为

// Move the file to the uploads dir
$new_file = $uploads['path'] . "/".date("YmdHis").floor(microtime()*1000).".".$ext;
if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) )
return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );

PS:整体代码其实就是替换掉了”/$filename”;

保存后覆盖原文件,那么上传文件就会以“年月日时分秒+千位毫秒整数”的格式重命名文件了,如“20121023122221765.jpg”

来源:https://www.boke8.net/auto-rename.html

注意事项

如果是修改的主题函数模板方式,在更新主题后,自己添加的代码,一般是会覆盖的,所以升级主题可以先做好备份。

如果是修改的程序源文件,升级程序后,程序升级后也是会被覆盖,也要做好备份。

以上方法请选择一种就好了。

给TA打赏
共{{data.count}}人
人已打赏
wordpress技巧

如何查看Wordpress网站使用是什么主题

2021-9-10 11:53:55

SEO技巧wordpress技巧

wordpress程序robots文件写法建议

2021-9-15 13:47:41

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索