Mary Dickson Diaz

Code, Life, Learning

how to use the wordpress rest api in rails

Folks, if you’re reading this over at www.marydickson.info, my Rails portfolio site, things are about to get real meta. Several weeks ago I RSVPed for a WordPress Developer’s meetup called Introduction to the REST API. I’ve used APIs with Rails, Angular, and in Twitterbots– an API (application program interface) is simply a way to transfer information from a server to a client, often using a format called JSON (JavaScript object notation). APIs are key to mobile apps that access the same database as a web based site. “REST” (representational state transfer) means that a system understands a set of standard verbs used to communicate over HTML, including: GET, POST, PUT, DELETE, etc. You can use an AJAX (asynchronous JavaScript and xml) call to transmit data via the REST verbs and either fetch data, post new data, update existing data, or delete a record, and the information will be persisted in a database somewhere behind the scenes.

That’s a lot of acronyms. Here have a picture:

how APIs work, sort of

Super! MARY, BUT WHY SHOULD WE CARE?

Long story short: I’ve had this WordPress blog since I started coding, and since then I’ve coded other web sites “from scratch,” including a professional portfolio site, that are much easier for me to customize and that add legitimacy to my claim of web developer. So that is what I want to share with potential employers but I *also* want them to see my awesome technical blog posts so they will think “She sounds cool and writes good. Let’s pay her money in exchange for her time!” UNTIL NOW the way to do that was to direct people to this site, marydickson.com, and hope that they will also go check out marydickson.info, or vice versa. Awkward.

The WordPress API allows me to import blog posts from marydickson.com and render them as a tab on marydickson.info. If you have any sort of non-WordPress site and you’d like to link to or display your blog posts, you can do that with the WordPress REST API. I’ll walk you through what I did to get this working in a Rails app:

#1 Read Darren Krape’s slides

I missed that Meetup but I used Darren’s slides to get started. There’s a lot here that I *didn’t* need, so don’t be intimidated, but I do want to give credit where due. The most important part is this:

#2 Install the WP REST API Plugin

It looks like this:

You can find it under “Plugins” on your WordPress dashboard. Install it and then activate it.

#3 You’ve got JSON!

After following the steps above, you should be able to go to http://www.yourdomain.com/wp-json/wp/v2/posts and see something that looks like this:

so beautious

so beautious

Don’t run away screaming, this is good. That query fetches all posts, and it also works for pages. If you want to filter your results, you can do so by passing parameters (everything after the question mark). For example, this particular endpoint is getting only the posts with category #25 (coding): http://marydickson.com/wp-json/wp/v2/posts?filter[cat]=25. For more options, RTFM (read the flipping manual).

#4 Build a framework to render your blog posts

From here I deviated from the slides and fell back on an exercise from Code Fellows 301 wherein students built a website to render blog articles from JSON. I added an HTML view to my page, just a placeholder really with an unordered list with id of “blog-posts,” so I’d have something to append my posts to.

<div id="blog" class="row">
<div class="large-12 columns">
<div class="row">
<div class="large-8 columns">
<h2>Recent Blog Posts</h2>
<ul id="blog-titles">
</ul>
</div>
</div>
</div>
</div>

*My tabs aren’t persisting in WordPress, but your code should be properly indented. 😛 We’re going to use JavaScript and JQuery to fetch the articles, which we’ll render as <li> elements inside that unordered list.

RAILS NOTES: Since I’m working in Rails, I created a new view in my static pages folder called welcome. So, this page’s file path is portfolio/app/views/welcome/blog.html.erb, and it corresponds to the Welcome controller that has an empty method called blog. Last, in my routes.rb file I set  get 'blog', to: 'welcome#blog' so that marydickson.info/blog would render the page.

OTHER NOTES:

  • This is a partial, which is why it doesn’t have any of the customary html headers and footers. Believe me, they exist.
  • You’ll need JQuery if your website doesn’t already have it.  Just add this line to your index.html page in the header or footer: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> (google JQuery CDN if that doesn’t work)
  • I don’t want to talk about all those divs, ok

#5 Set up your JavaScript

Now for the fun part!

Let’s break down what’s happening here:

  1. function Article(object){…} — this is declaring an Article constructor function that takes in an object and creates a singular Article instance (one blog post). It retrieves values from that object and assigns them to properties we can use: title, link, excerpt, and image (if exists).
  2. Article.prototype.toHtml = function(){…}  — this is a prototype function that can be called on any Article instance. This particular function returns an html string that is basically a list item with some formatting. “This” in the code refers to the article that is the subject of the function call, so if I were to call .toHtml on this current article, this.title would equal “how to use the wordpress rest api in rails”. (*head explodes* so meta)
  3. Article.loadall(){…} — this is a function called on the Article constructor itself, rather than an instance of an Article. After we have this constructor function object called “Article”, we can add things to it, like functions and properties. This function is saying: create a new property on Article called Article.all, and set it to the results of mapping the rawdata we get back from our AJAX call (hang on, we’re getting there) and running each object through the constructor function. So Article.all becomes an array, or list, of articles.
  4. Article.render(){…} — another function that  takes our new shiny array and uses some JQuery to attach the results of each article.toHtml to our page. You’ll recall that .toHTML returns a list item, so we append it to that empty list.
  5. The heart of it all: this is that AJAX call that fetches the JSON data from WordPress, assigns it to a rawData property, and then invokes the two previous functions, causing them to run.
  6. Last step: add this line <script> Article.ajaxCall() </script> somewhere in your html, to invoke the ajax call — I added it right in the html, which is not a best practice, but was necessary for correct rendering based on how I structured my Rails app.

RAILS NOTES: I created a new file article.js in portfolio/app/assets/javascripts/, and then added this line to application.js: //=require article. Don’t forget to precompile before you deploy (ABPC: Always Be Pre-Compiling) with a  bundle exec rake assets:precompile, and you’re golden!

OTHER NOTES:

  • I decided to render a blog preview only, with a “read more” tag to direct readers to this WordPress site for the full article. The formatting over here is nicer, and the excerpts give portfolio scanners an idea of what I’m writing about, with the option to click through. You can fetch the entirety of the blog post instead if that’s what you’re looking for.
  • I skipped over explaining the weird code connected to “this.image.” Basically, I’m using some regex magick to scan the post and see if it has an image; if yes, display it.
  • I’m only using the “GET” command here to fetch blog posts. If I wanted to, I could build a form to delete, update, or add new posts direct from the page. I don’t actually want to do that, but thus is the magic of REST. 🙂

#6 HEY THANKS RACHEL BAKER!

Now your blog posts are rendering on your professional site, employers are going to be hella impressed, you’re definitely gonna get hired and paid boatloads of money, and adding to this pile of awesomeness, we have Rachel Baker to thank for this female-led initiative. Could not love this any more.

And that’s it! I admit I am mining only the tip of the iceberg here, but I don’t know PHP and I’ve only just started to investigate WordPress development. What are your plans for using the WordPress API?

1 Comment

  1. Hi there. One thing I’m not sure about here is I had a free account. I just upgraded to a paid account in order to get plugins. It is now telling me that a custom domain name is required to install the WP REST API plugin. I already have a RoR site. I just want to add my wordpress blog to http://www.mysite.com/blog. What should I choose as my WordPress custom domain?

Leave a Reply

© 2017 Mary Dickson Diaz

Theme by Anders NorenUp ↑