Ruby/WordPress
Too long? tl;dr.
Situation: You’re migrating a big site to WordPress. You don’t want to make 1,000+ posts manually, do you?
Meet Ruby/WordPress. I’ve made a quick little Ruby gem that interfaces with your WordPress database, so you can manipulate it within Ruby. This opens up a whole world of possibilites - the most exciting being Nokogiri, of course.
Here’s a quick code sample that will create 100 new posts!
require 'wordpress'
# Configuration
wp = WordPress.new { host: '127.0.0.1',
port: 3306,
username: 'test',
password: 'test',
encoding: 'utf8',
database: 'wordpress',
wordpress_prefix: 'wp_' }
(1..100).each do |i|
post = wp.new_post { post_name: "post-#{i}",
post_status: 'publish',
post_title: "Post #{i}" }
post.post_content = "This is the content for post #{i}"
post.save!
end
Note that the configuration must point to a valid WordPress database (and make sure you don’t use one with valuable data… I don’t take responsibility for any lost data. You should be backing up anyways.)
It’s at version 0.0.2, a very early beta at this point, but it can do basic tasks such as creating posts (as shown before) and post querying (albeit, very basic at this stage in development):
wp.query( post__in: [ 1, 5, 8] ).each do |post|
puts "Post: #{ post.post_title }n"
end
wp.query( post_type: 'custom_post_type', post_parent: 10 ).each do |post|
puts "Post: #{ post.post_title }n"
end
The ultimate goal of WordPress#query
is to be fully compatible with the WP_Query
API.
Another feature is post meta manipulation. After you get your post
object ( WordPress::Post
), getting or setting post meta is very easy:
post.post_meta['hello'] = 'world'
puts post.post_meta['hello'] + "n"
Initial support for taxonomies is also included:
puts post.get_the_terms('category').join(', ') + "n"
post.set_post_terms ['love', 'WordPress'], 'category'
Note: WordPress::Post#set_post_terms
will overwrite all terms of the given taxonomy, unless you supply the “append” flag:
post.set_post_terms ['love', 'WordPress'], 'category', true
As you can probably tell, this is not a very ideal API, and I am planning on changing it soon.
Contribution
Contributions are very welcome!! If you have an idea, or something that you would like to contribute, but don’t feel like you have something concrete enough for a pull request yet, please don’t hesitate to open an issue or contact me directly.
How to Install
Ruby/WordPress can be installed via RubyGems:
$ gem install ruby-wordpress
or, if you use Bundler:
gem 'ruby-wordpress', :require => 'wordpress'
Links: