Here at Big Fish, we use WordPress for all our client sites. It’s a robust, mature, and simple content management system that has a huge ecosystem of preexisting plugins surrounding it; we’ve developed our own bespoke library of plugins that give us common functionality for our clients’ sites; and importantly, it’s incredibly easy for even non-technical users to administrate.
We like it a lot. But in my heart, I’m a Rubyist. I love the ecosystem, I love the community, and I just plain enjoy writing Ruby code.
These two facts have been in tension for a while, then. While our public-facing, web-based code is inevitably going to be written in PHP and integrate directly with WordPress, what about other code? We often want to interact with WordPress from a cron job, or a daemon, where PHP might not be the most sane choice.
This desire to manipulate WordPress from within Ruby led to a project I ended up calling ruby-wpdb. It’s an ORM (object relational mapper) for WordPress databases, written in Ruby; that means it has models for all of the objects that the WordPress database represents, and allows you to manipulate the content of your WordPress site directly in Ruby.
So a post, stored in the
wp_posts table, is a
post = WPDB::Post.new(post_title: 'Hello, world', post_content: 'This is your first post!')
And a comment, stored in the
wp_comments table, is a
comment = WPDB::Comment.new(comment_author: 'Mr. WordPress', comment_author_email: 'email@example.com', comment_content: 'This is a comment')
And so on; you get the picture.
As well as creating objects, you can of course also query the ones that already exist. For example, to fetch all of the posts with the status “draft”, you could call:
draft_posts = WPDB::Post.where(post_status: 'draft').all
Fairly self-explanatory too, I think.
If you’d like to learn how to use ruby-wpdb, then read on.
ruby-wpdb is a Ruby Gem, so you can install it with a simple:
$ gem install ruby-wpdb
If you receive a permissions error, you may need to call
install ruby-wpdb instead.
Connecting to your WordPress installation
Next, you need to tell ruby-wpdb where it can find the database that
contains your WordPress install. To do this, it needs to know the same
information that you’d put in your
wp-config.php: your database host,
username and password, and database name.
So if you had an install of WordPress in a database called “database_name”, on your local server that you access with the username “root” and the password “pa55w0rd”, you’d set up ruby-wpdb with:
require 'ruby-wpdb' WPDB.init('mysql2://root:pa55w0rd@localhost/database_name')
That’s all there is to the setup! You can now start accessing your WordPress data.
Here’s a quick example to get you started, but there’ll be more in the next article. This code should output the title of your most recent post:
latest_post_title = WPDB::Post.reverse_order(:post_date).first.post_title puts latest_post_title