Sometime ago I uploaded all images of my wordpress installation to the /media/ folder. So urls where something like this:


This folder is very, very big. So I switched to a date folder structure:


So I wrote a plugin to loop through all images to get the url. Here is a excerpt:

foreach ($posts as $post):
  $featured_image_url = wp_get_attachment_url(get_post_thumbnail_id( $post->ID ));
  echo featured_image_url;

Nearly half of my images have still the flat media-folder structure. But I want to delete all images in the root of the media folder and sort them with date folders.

So my idea is to copy the files to the corresponding folder of the post and change the url of the featured image attachment. But there is no wordpress way to change urls with a function. Is there a trick to it? I looked in the database and I don't really understand how the connection between a featured image and a posts works.

How can I change the url of a featured image?

1 Answer 1


Featured images are actually associated by ID, not URL. So, as long as when you move the images (I assume via FTP) you also update the image URL in the database, you won't have to update any of the posts that use the images as a featured image.

WP stores the image URL as postmeta. So, for each attachment, you'll need to find the post ID, then search for the _wp_attached_file postmeta key for that particular post ID. Once you find that, you can edit it to add in the year and month.

So you should find something like

_wp_attached_file = media/file.jpg

and change it to

_wp_attached_file = media/2018/06/file.jpg

if it should be in the June 2018 folder.

-- But -- if you also use any of these images anywhere in actual post content, that part does not automatically update. So, you would also have to update each individual post that contains these images (you should be able to search for them in phpmyadmin, or you could use your existing code to find all the urls and then build a regex to match any that don't have the year and month in the URL, and add more code to determine what month and year they need to go in and update that value in the database too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.