假设我上传了一个例如图片的媒体文件,其名称为example_123_56737_303030.png
,但在上传之前我希望将此图片名称更改为我选择的任何内容(最好是此附件的post_id)所以它看起来像122.png(122是这个附件的post_id)。
现在需要实现的目标是:
_wp_attached_file
,_wp_attachment_metadata
表中的wp_post_meta
应该是新名称。答案 0 :(得分:0)
将以下代码放入 functions.php
function handle_uploadedimage($arr) {
// Get the parent post ID, if there is one
if( isset($_REQUEST['post_id']) ) {
$post_id = $_REQUEST['post_id'];
} else {
$post_id = false;
}
// Only do this if we got the post ID--otherwise they're probably in
// the media section rather than uploading an image from a post.
if($post_id && is_numeric($post_id)) {
// Get the post slug
$post_obj = get_post($post_id);
$post_slug = $post_obj->post_name;
// If we found a slug
if($post_slug) {
$random_number = rand(10000,99999);
$ext = pathinfo($arr['name'], PATHINFO_EXTENSION);
$arr['name'] = $post_slug . '-' . $random_number . '.'.$ext;
}
}
return $arr;
}
add_filter('wp_handle_upload_prefilter', 'handle_uploadedimage', 1, 1);
您也可以尝试以下版本
function handle_uploadedimage($arr) {
$random_number = md5(rand(10000,99999));
$ext = pathinfo($arr['name'], PATHINFO_EXTENSION);
$arr['name'] = $random_number .'.'.$ext;
return $arr;
}
add_filter('wp_handle_upload_prefilter', 'handle_uploadedimage', 1, 1);
你也可以尝试这个插件wordpress.org/plugins/file-renaming-on-upload/screenshots,这会更好我猜