Rename wordpress when uploading images-some problems encountered when modifying the plug-in, wordpress uploads images

Source: Internet
Author: User

Rename wordpress when uploading images-some problems encountered when modifying the plug-in, wordpress uploads images

Wordpress is a blog platform developed in php language. It is highly scalable and easy to expand and is suitable for secondary development.

1. Problem Origin

This Friday, when I browsed the company's website (based on wordpress development), I found that there were two thumbnail copies on the homepage of the website, so I went to the background to check the website, I want to see if an employee chooses the same picture as the cover image when writing the article.

The results showed that the names of the album art images used in these two articles were the same, but I thought that employees would not make such a mistake again if they were confused. So I checked the URLs of the cover pictures in the following articles. These addresses are the same.

I think it may be that the two images have the same file name (as to why this happens, I am afraid only the ghost knows). After the file is uploaded, the uploaded image overwrites the previously uploaded image, and only one image is left on the cloud storage server.

Note: I have written a plug-in to upload images to Baidu cloud's BOS.

 

2. How to solve the problem

In fact, at the beginning, I was very entangled in this problem: Let the staff who edited the article pay attention to it next time, each time you upload an image, you need to re-name the image by year, month, day, plus number, and other image information before uploading it, or do I add some code in my plug-in to rename the image silently?

Well, here, you can certainly guess what kind of choice I made? Write code.

 

3. twists and turns

My plug-in was originally only responsible for uploading images to Baidu cloud's BOS, and then deleting local images, mainly using the wordpress wp_update_attachment_metadata hook. I called a self-defined function upload_attachement_to_bos in this hook,

This function uploads images to BOS and deletes local images. At the beginning, I was thinking about how to write an article in this function: Rename the source image, rename the thumbnail, the amount, and try it for half a day. I checked the image on BOS. the upload was successful and the file name was modified.

Why does the url of the website image remain unchanged?

Don't worry. Check the image under the library first. The results show that the image file name, title, and url in the library are still the original file name.

Although I changed all the file names on the server, the values of image-related fields in the database were not changed. So I tried to change the wordpress data table to see if the image file name in the library and article thumbnail has changed.

During this period, I tried to modify the postname, post_title, and guid fields in the post table, but it was useless. Postname: the alias of an article, which is displayed in the url address. It can be used to beautify the url address. post_title: corresponds to the image title on the attachment details form page in the media library, which is equivalent to the article title,

Guid: Well, to be honest, I don't know what it is, as if it is the unique identifier of the article.

Finally, I located meta_key: _ wp_attached_file IN THE postmeta table. The value of _ wp_attached_file affects the attachment information of the document. For example, the image url and file name on the attachment details page in the media library are all the meta_value values.

This is also the value of the file name in the homepage Article thumbnail and header image url on the single page under the wordpress topic (several topics I tested.

Well, the root cause is finally found. The problem is how to modify the value.

 

4. The problem is solved temporarily, but there are still some legacy problems.

As mentioned above, I used the wp_update_attachment_metadata hook, so I used the corresponding hook function to modify the file name and update _ wp_attached_file. The hook function code is roughly as follows:

1 // hook function: Rename the file, update the file meta information, call the upload function, and save the path information of the uploaded source image in the bucket to database 2 function update_attachment_metadata ($ data, $ post_id) {3/* rename the file to prevent conflicts */4 date_default_timezone_set ('prc'); 5 $ wp_upload_dir = wp_upload_dir (); 6 $ old_path = $ wp_upload_dir ['basedir']. '/'. $ data ['file']; 7 $ ext = pathinfo ($ old_path, PATHINFO_EXTENSION); 8 $ old_namestr = str_replace ('. '. $ ext, '', basename ($ data ['file']); 9 $ new_namestr = date ('ymdhis -'). dechex (mt_rand (100000,999 999); 10 $ new_path = $ wp_upload_dir ['path']. '/'. $ new_namestr. '. '. $ ext; 11 12 rename ($ old_path, $ new_path); 13 14 if (isset ($ data ['sizes']) & count ($ data ['sizes'])> 0) {15 $ thumb_data = & $ data ['SIZE']; 16 foreach ($ thumb_data as $ key => $ thumb) {17 $ old_thumbpath = $ wp_upload_dir ['basedir']. '/'. substr ($ data ['file'], 0, 8) 18. $ thumb ['file']; 19 $ new_thumbpath = str_replace ($ old_namestr, $ new_namestr, $ old_thumbpath); 20 if (file_exists ($ token) {21 rename ($ old_thumbpath, $ new_thumbpath); 22} 23} 24} 25/* update the file name in data */26 $ old_jsdata = json_encode ($ data, JSON_UNESCAPED_UNICODE ); 27 $ new_data = json_decode (str_replace ($ old_namestr, $ new_namestr, $ old_jsdata), true); 28 29 unset ($ data, $ old_jsdata ); 30 31 $ ori_object_key = upload_attachement_to_bos ($ new_data, $ post_id); 32 // Add the path information (object Information) of the original image in the BOS bucket to the database 33 add_post_meta ($ post_id, 'bos _ info', $ ori_object_key); 34 35/* update the value of _ wp_attached_fies in the postmeta table */36 $ old_meta = get_post_meta ($ post_id, '_ wp_attached_file ', true); 37 update_post_meta ($ post_id, '_ wp_attached_file', str_replace ($ old_namestr, $ new_namestr, $ old_meta); 38 39 return $ new_data; 40}View Code

The key is to modify the value of _ wp_attached_file in the postmeta table in rows 36 and 37. Note that I have processed the return value of the function here, the returned $ new_data array is the array after the file name is replaced. I do not know if this will cause any side effects.

Then, I updated the plug-in code. Well, the plug-in works. The renaming function is implemented, and the original function is not damaged.

 

5. Other issues

(1) The $ data array in the Code is a multi-dimensional array. How to replace the multi-dimensional array with strings? The str_replace () function seems to be able to replace only one-dimensional arrays. In the code, I used to convert the array into a string and then replace it with json_encode () and json_decode (). I don't know if there are other better methods.

(2) rename (): Before renaming a file, you must first determine whether the file exists and the folder permissions (or modify the folder permissions if the permissions are insufficient ), I did not do this here.

 

Ps: I wrote this wp-bos plug-in (supporting wordpress using cloud storage as the image storage space, and currently supporting BOS Baidu cloud storage) hosted on gitoschina and github,

However, the hosted code has not yet added the rename function. After the plug-in runs on the website for a period of time, I will promptly push the changes. If you are interested, please stay tuned.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.