du512053619 2016-01-22 05:03
浏览 42
已采纳

如何在上传时从WordPress后端和前端更改媒体文件的名称?

Suppose I uploaded a media file for eg image, and its name is example_123_56737_303030.png but before upload I want this name of the image to be changed as any thing of my choice (best will be post_id of this attachment) so it looks like 122.png (122 is the post_id of this attachment).

Now the things that needs to be achieved is :

  1. Name should be changed when I upload the file from back-end/front-end/directly in media/In post/In page/Any custom post type (means if media is uploaded from anywhere in the wordpress website).
  2. The serialize data which wordpress saves for every image, that are _wp_attached_file, _wp_attachment_metadata in wp_post_meta table should be as per the new name.
  3. The image should be of the new name in the folder as well (upload place/directory is fine no changes required in that).
  • 写回答

1条回答 默认 最新

  • dongqiyang3711 2016-01-22 05:55
    关注

    Put below code into your 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);
    

    You can also try below version

    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);
    

    You can also try this plugin wordpress.org/plugins/file-renaming-on-upload/screenshots which will be better I guess

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog