2016-01-22 74 views
0

假设我上传了一个媒体文件,例如图片,它的名字是example_123_56737_303030.png,但是在上传之前,我希望这个图片的名称被改变为我选择的任何东西(最好是这个附件的post_id),所以它看起来像122 .png(122是此附件的post_id)。如何在WordPress后端和前端上传时更改媒体文件的名称?

我们实现需要的东西是:

  1. 名称应该当我上传从后端/前端文件/ /改为直接在媒体邮寄/在页/任何自定义帖子类型(意味着如果媒体从WordPress网站的任何地方上传)。
  2. wordpress为每个图像保存的序列化数据,即_wp_attached_file,_wp_attachment_metadatawp_post_meta表中应该按照新名称。
  3. 该图片应该是该文件夹中的新名称(上传 位置/目录很好,不需要进行任何更改)。

回答

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这会更好我猜

+0

不工作..文件名仍然是一样的 –

+0

我修改了代码.. pl。检查 –

+0

是啊!谢谢 –

相关问题