This tutorial is based on the presumption that you are running a Wordpress installation greater than (or equal to) version 3.4. The XML RPC API was released in Wordpress 3.4 which is a requirement for the code featured in this tutorial to work. In Wordpress versions 3.5+ the XML RPC API is turned on by default. In versions of Wordpress prior to 3.5, the setting can be found in Settings > Writing > Remote Publishing.

So you have a Wordpress installation hosted somewhere and you want to move across your Wordpress posts to a Rails app and into the target Rails model of your choice? Well I have a very simple script that'll do that for you.

You can use the rails runner command to execute a standalone ruby script within the context of your Rails application. This means that you can access your Rails models within the standalone script. The easiest way to do this is to use a require statement to import the relevant environment into your script (I'm importing my development environment in the example code below). Please replace the XXX's below with your Wordpress installation's credentials (it won't work otherwise!).

A few notes on the script:

- The script will only pull in posts from your Wordpress installation that have the 'Published' status

- You will need to add the Rubypress gem into your Gemfile. i.e. gem 'rubypress'  and run bundle install before proceeding

- For each post imported from the Wordpress API, I convert to my 'Article' model. Your target model will most probably be named something else and will likely have different field names; change the script accordingly.

- I stuck my script into the root of my Rails application, and I named it wordpress-import.rb. To run the script, run rails runner wordpress-import.rb. If you want to run the script on heroku to populate your production database, run heroku run rails runner wordpress-import.rb

Here is the script:

require 'rubypress'
require 'date'
# Import the relevant environment
require File.expand_path('config/environments/development.rb')
require 'json'

# Clear all articles beforehand
Article.delete_all

wordpress = Rubypress::Client.new(:host => "XXX", :username => "XXX", :password => "XXX", :retry_timeouts => true)

wpPosts = wordpress.getPosts(:filter => { :number => 100, :orderby => 'post_id', :post_status => 'publish' })

# enumerate each wordpress post
wpPosts.each do |wpPost|
    Article.create!(
        :title => wpPost["post_title"],
        :content => wpPost["post_content"],
        :created_at => wpPost["post_date_gmt"].to_date
    )
end

And that is literally it. A potentially tricky Wordpress migration done in under 20 lines of code. Ah, the beauty of it.

Adam n' out