Hey there, fellow code wranglers! Ready to dive into the world of WordPress API integration with Ruby? Buckle up, because we're about to embark on a journey that'll make your Ruby apps and WordPress sites play together like best friends. Whether you're looking to pull in blog posts, push content, or just show off your API prowess, this guide's got you covered.
Before we jump in, let's make sure we've got our ducks in a row:
httparty
, dotenv
(trust me, you'll thank me later)First things first, let's get you authenticated:
.env
file:WP_API_URL=https://yoursite.com/wp-json/wp/v2
WP_USERNAME=your_username
WP_PASSWORD=your_app_password
Pro tip: Use application passwords, not your actual login. Safety first!
Let's create a simple client class:
require 'httparty' require 'dotenv/load' class WordPressClient include HTTParty base_uri ENV['WP_API_URL'] basic_auth ENV['WP_USERNAME'], ENV['WP_PASSWORD'] def get_posts self.class.get('/posts') end end
Boom! You're ready to rock.
client = WordPressClient.new posts = client.get_posts puts posts.first['title']['rendered']
Add this method to your client:
def create_post(title, content, status = 'publish') self.class.post('/posts', body: { title: title, content: content, status: status }) end
I'll leave these as an exercise for you. (Hint: use PUT
and DELETE
requests)
Custom post types are just like regular posts, but cooler. Fetch them like this:
def get_custom_posts(type) self.class.get("/#{type}") end
Uploading media is a bit trickier, but nothing you can't handle:
def upload_media(file_path) self.class.post('/media', body: File.read(file_path), headers: { 'Content-Disposition' => "attachment; filename=#{File.basename(file_path)}" } ) end
Don't let errors catch you off guard. Wrap your requests in begin/rescue blocks and log liberally:
begin response = client.get_posts # Do something with the response rescue => e logger.error "Failed to fetch posts: #{e.message}" end
Cache aggressively and respect rate limits. Your WordPress server will thank you.
Write tests. Seriously. Your future self will buy you a coffee.
require 'minitest/autorun' class TestWordPressClient < Minitest::Test def setup @client = WordPressClient.new end def test_get_posts posts = @client.get_posts assert_instance_of Array, posts refute_empty posts end end
Keep those API keys safe! Use environment variables in production, and maybe consider API versioning to avoid surprises.
And there you have it! You're now armed and dangerous with WordPress API integration skills. Remember, with great power comes great responsibility – use your newfound abilities wisely. Now go forth and build something awesome!
Need more? Check out the official WordPress REST API Handbook. Happy coding!