Create a gist now

Instantly share code, notes, and snippets.

@kynatro /README.md
Last active Jul 20, 2016

Embed
WordPress Upload Import

Import images from an old WordPress blog to a new server (or local environment)! This simple script uses wget to download the file and place it in a corresponding local wp-content/uploads folder.

Wait, but why?

WordPress' import script is really dumb when it comes to images - even if you have the box checked to "download and import attachments", it won't actually download any images placed in your post content. This script does the download portion, but and you'll need to update the database separately.

Usage

  1. Update the urls array with your list of URLs
  2. Execute the script from your WordPress root: ruby import-wp-uploads.rb
  3. Update your database entries to use the new local images

Bonus: Update your database entries

Here's an example SQL command you can run to update all your wp_posts entries to point to the new local location instead of the old URL you imported from:

UPDATE wp_posts
SET post_content = REPLACE(post_content, 'oldblog.com/wp-content/uploads', 'newblog.com/wp-content/uploads')
WHERE post_type = "post"

Of course, in the above SQL you should update the table name to match your site's prefixing and update the URLs being repalced.

require 'fileutils'
# A list of URLs for the upload files in your originating WordPress blog
urls = ["http://www.dtelepathy.com/blog/wp-content/uploads/2015/03/han-solo_orders-684x1024.jpg", "http://www.dtelepathy.com/blog/wp-content/uploads/2015/12/Warp-Speed.gif"]
urls.each do |url|
parts = url.split("/")
filename = parts.pop
month = parts.pop
year = parts.pop
uploads_base = "wp-content/uploads"
folder_path = "#{uploads_base}/#{year}/#{month}"
file_path = "#{folder_path}/#{filename}"
if !File.directory?("#{folder_path}")
FileUtils.mkdir_p("#{folder_path}")
end
system "wget #{url} -O #{file_path}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment