重命名和覆盖上传的文件 [英] Rename and overwrite uploaded files
问题描述
我使用以下代码将图片上传到 Wordpress
I use the following code to upload images to Wordpress
function custom_upload_name($filename)
{
$info = pathinfo($filename);
$item_id = $_POST['item_id'];
$filename = $item_id . '.jpg';
return $filename;
}
add_filter('sanitize_file_name', 'custom_upload_name', 10);
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$item_id = $_POST['item_id'];
$uploadedfile = $_FILES['file'];
$image_name = $item_id;
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
//file is uploaded successfully. do next steps here.
echo $location_home .'/images/' .$image_name . '.jpg';
}
文件的重命名工作正常.但是我选择同一张图片两次上传一切都很好,但是如果我选择了不同的图片来上传,Wordpress 会自动在文件中添加一个数字:
The renaming of the files works correctly. But I select the same image twice to upload everything is fine, but if I select a different image to upload, Wordpress automatically adds an number to the file:
- 第一次上传的结果:10000.jpg
- 第二次上传的结果(相同的文件,相同的 ID):100001.jpg
- 第三次上传的结果(相同的文件,相同的 ID):1000012.jpg
如何让 Wordpress 自动覆盖具有相同 id 的文件,而不会给文件添加额外的数字?
How to let Wordpress automatically overwrite the files with the same id, without adding extra numbers to the file?
推荐答案
使用这段代码,unique_filename_callback
是回调函数,这个函数是wordpress自动调用的.所以我们可以覆盖同名的文件.
Use this code, unique_filename_callback
is call back function, this function automatically called by wordpress. So we can overwrite the files with same name.
$upload_overrides = array( 'test_form' => false,'unique_filename_callback' => 'my_cust_filename' );
// You codes
function my_cust_filename($dir, $name, $ext){
return $name.$ext;
}
这篇关于重命名和覆盖上传的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!