Prakash Rao
Prakash Rao

Reputation: 2398

How to change the name of media files at the upload time from WordPress back-end and front-end?

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

Upvotes: 0

Views: 2545

Answers (1)

Mayur Chauhan
Mayur Chauhan

Reputation: 731

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

            // If we find post
            if(!empty($post_obj->post_name)) {
                $post_slug = $post_obj->post_name;
                $random_number = rand(10000,99999);
                $ext = pathinfo($arr['name'], PATHINFO_EXTENSION);

                //Write your logic to remove any special characters from file name
                $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

Upvotes: 1

Related Questions