I’m dealing with a WordPress site that has hundreds of image URLs containing random numbers in their paths that need to be removed. The problem is that each image has a different unique number, so I can’t just do a simple find and replace operation.
As you can see, I need to strip out that random number folder (like 98765432) that appears after the date but before the actual filename. Since every image has a completely different number, standard search and replace won’t work.
Is there a way to handle this programmatically using PHP code or maybe direct database queries? I’m looking for a solution that can identify and remove these numeric folders automatically without having to manually edit each URL. Any suggestions on the best approach for this bulk update would be really helpful.
Had this exact issue with a client’s site using a garbage upload plugin. The database approach works, but don’t forget wp_postmeta - that’s where attachment metadata lives. I wrote a custom script that updates the guid field in wp_posts AND the _wp_attached_file meta value in wp_postmeta. Here’s the kicker: WordPress caches attachment URLs like crazy. After your database updates, clear all caching plugins and regenerate thumbnails. Also check if your theme stuffs any URLs in customizer settings or widgets - those sit in wp_options and your standard media updates won’t touch them. This took me forever because I missed those edge cases first time around.
Run a database query on the wp_posts table to update all your media URLs at once. Try UPDATE wp_posts SET post_content = REGEXP_REPLACE(post_content, '(/wp-content/uploads/[0-9]{4}/[0-9]{2}/)[0-9]+/', '$1') WHERE post_type = 'attachment' - that should work. Don’t forget to check your wp_options table for hardcoded URLs in theme settings. I had the same problem after migrating from a plugin that created those random folders. This method cleaned up 800 images in one shot. Test it on staging first though - you can’t easily undo database regex operations.
Regex works great for this. Try preg_replace('/(\/\d{4}\/\d{2}\/)\d+\//', '$1', $url) in a loop through your media URLs. Backup your database first - regex can get messy if the pattern doesn’t match right.