Real World WordPress REST API Usage – YIKES!

By Evan Herman

August 24, 2016

Say what now?

By now, I’m sure you’ve heard a ton of information about the new WordPress REST API coming to a future releases of WordPress. You may notice others getting excited, or gearing up for a major overhaul of the WordPress infrastructure. It’s all the rage at WordCamps over the past year, and you see articles popping up on sites like Torque and WP Tavern.

When I first heard that a new REST API was coming to WordPress, I too was excited. I didn’t know why, and I couldn’t think of any real world uses for it – mainly because I didn’t understand what it was. But I knew that it was going to be a game changer, and something that developers should at least become familiar with. As the web moves towards web applications, the REST API is going to play an integral part in the way data flows through your site. Further down the road, building out a REST API within WordPress allows WordPress to communicate with other technologies – further widening the “Internet of Things” – transforming your website into a data mine.

In this article I am going to explain what the REST API is (in layperson’s terms), how you or your agency can benefit from it, and provide a real world example or two. My goal is to provide a basic understanding of the REST API and some of its capabilities, as well as provide you with some working code that you can implement, use a starting point or as inspiration.

What is this REST API you speak of?

REST stands for Representational State Transfer and is a web architecture style. REST is essentially a method of communication between one or more web services, allowing you to send or retrieve data between sites that lie on different hosting environments. One of the benefits of REST is its decoupled architecture. This means that each component that makes up a WordPress site is completely independent of one another. This allows you to do some truly custom work – from building out custom admin dashboards to fully functional themes utilizing Angular.js or React.js.

Building out a theme with Angular.js or React.js creates a seamless website – where posts and pages load near instantly and without the need for a full page refresh – providing a much better end user experience.

Ok…But Why?

At this point, you may be asking yourself “Ok…cool…but Why?” You may be thinking, “Why fix something that isn’t broken?” WordPress works perfectly fine now, why reinvent the wheel? And you would be perfectly valid in thinking that. One of the major reasons is building out a REST API guarantees WordPress’ spot as a full fledged application platform. Here are just a few reasons why moving towards a fully RESTful WordPress is the future, and why you should consider embracing it:

  1. Removes any reliance on PHP. WordPress is built using PHP while the REST API removes the reliance of PHP altogether. This is a great thing as it opens the gates to additional developers, from other communities and languages – widening the number of active developers who have the skill and knowledge to work on the WordPress project.
  2. Decoupled Architecture. I briefly touched on this above, but with the full separation of the front end and dashboard of your WordPress sites users now have the ability to fully re-imagine the dashboard for their specific use case. Each project you work on can have a fully customized environment – allowing you to provide the best possible solution to your clients. Additionally, a decoupled front end allows for content to be served from any device or medium.
  3. True Mobile Integration. Having a way to interact with the database via a REST API will allow for a truly mobile experience. This would allow both iOS and Android developers to build out applications that interact with WordPress sites – using native languages such as Swift or Java.

Real World Examples

Now that you have a better understanding of what REST stands for, what the REST API is and why you might use it. Let’s get into some use cases in the real world. Keep in mind that you can use as much or as little of the REST API as you’d like, meaning you can construct an entire theme using it, you can expose your custom post types to the REST API endpoints, or you can use it to retrieve standard post type data for things like widgets or shortcodes.

A few themes built out using the REST API can be found on Github, built out by some popular developers:

  1. Rachel Baker – WCUS Demo Theme
  2. Roy Sivan – Angular WordPress Theme

A beautiful example of a full featured site built on top of the WP REST API, built out by Human Made LTD., can be found at ustwo.com. One thing you will notice about the site is how fast it loads, and how fast it is to switch between pages. Since the REST API is sending JSON (JavaScript Object Notation) data between the server and browser, the DOM is lightning fast to render.

Alongside your REST API compatible themes, there are a number of plugins in the WordPress.org plugin repository that are compatible in one way or another with the REST API. Some of the tools available alter the way the REST API functions (by customizing the endpoints, altering the data returned, altering the key names etc.), while others build in support to their plugins by enabling post types or taxonomies to be retrieved via the REST API. Some helpful plugins/tools to extend the REST API functionality are listed below:

  1. WP REST API Controller – This plugin, built by the YIKES Inc. team, enables a UI in the dashboard, allowing users to toggle visibility of custom post types, customize endpoints and REST API properties.
  2. WP API Menus – Expose menu items to the REST API, so you can query items and build custom menus using the REST API.
  3. WP REST API Log – Plugin which logs WP REST API requests and responses. Helpful for debugging.
  4. WP REST API Cache – Enable caching for WordPress REST API and increase speed of your application.

For a full list of compatible plugins, see WP REST API Compatible Plugins & Tools.

Extending the REST API with Custom Endpoints

We mentioned you could extend the API endpoints to allow your custom post types, registered using register_post_type(), to be accessed by API requests.

First we’re going to setup a demo post type to use as our example. We will also assign a meta field to the post type, so we can demonstrate how easy it is to expose custom meta data to those endpoints as well.

Keep in mind if you are following along with the tutorial here, you will want to copy all code mentioned into the functions.php file of your active theme. If you are unsure of how to edit that file, you can use a third party plugin to add all of this code to your theme safely. One plugin that we highly recommend is ‘My Custom Functions.’

Additionally, it is assumed that you have the WP REST API (version 2) plugin installed on your WordPress site. Without the plugin installed and active, you’re not going to be able to properly access the post type data using the REST API endpoints.

After you add the above code to your themes functions.php file, refresh the admin dashboard, and you will see a new menu item in the left hand side ‘Sample Post Types.’

Screenshot:
sample-post-type-menu-item

Next, we will want to create a new meta box and a new field to assign to our post type. We will use a standard text input field, but this could really be any type of field you want. Copying the following block of code will generate a new metabox

The following block of code will define our new metabox, and assign it to the ‘sample_post_type’, that we created in the previous step. Additionally, we will include a function to include the saving of the metabox data. Again, you will want to copy the entire code block below directly into your active themes functions.php file, or into the ‘My Custom Functions’ plugin.


sample-post-type-metabox

Now that we have a sample post type setup with a custom meta box and some meta data to work with, we can continue with adding our post type and meta data to the rest api endpoints so we can properly retrieve the data.

Expose the Post Type

Now we will need to hook into the WP REST API plugin, and use the built in action hooks to add our post type the list of available post types. The documentation on the WP REST API site is great for outlining the process, if you want some additional reading.

You can copy and paste the following block of code into your themes functions.php file. If you are using the sample post above, copying & pasting will work just fine. If you have your own custom post types you have defined, you will want to populate the $post_type_array with all the post types you’d like to enable in the REST API.

Once you’ve added the above code block to your themes functions.php file – you should then be able to access the custom post type via the REST API. If you were using the post type outlined above, your new endpoint would be http://www.example.com/wp-json/wp/v2/sample_post_type but if you were using a different post type, the path at the end of the URL would be different and would end with the post type name. For example, if your post type was ‘jobs’ your end point would be http://www.example.com/wp-json/wp/v2/jobs.

It’s important to note that you can customize the base of the URL in the function above. If you wanted to alter the rest_base, you would just need to change $wp_post_types[$post_type_name]->rest_base = $post_type_name; to something other than $post_type_name.

Viewing the end point for our custom post type, you will notice that our custom metabox/meta data isn’t listed with all of the other data. You will see some of the standard data such as the post ID, date, date_gmt, modified, modified_gmt, slug, type, link, content etc. But our metadata is no where to be found.

In the next step, we will add our metadata to our custom post type end point – so we can access the custom meta data for each individual post.

Expose Custom Metadata

Now we will hook into the WP REST API action rest_api_init, where we can define a new field to add to our API response. In our case, we will add ‘sample_post_meta’ to our response, so we can retreive the data assigned to each post for our custom, sample, metabox we created above. The following code snippet can be copied right into your themes functions.php file, and if using the examples above, will start working. If you are using a different post type, you will want to change “sample_post_type” in the code block below to your respective post type. If you have multiple post types, you will want to use register_api_field multiple times.

The second thing to tweak is “sample_post_meta“, which should be equivalent to the name of your meta field that you created in the steps above. This should be equivilent to the meta name if you were going to use get_post_meta() to get the meta data. In the example above, the field name is ‘sample_post_meta’.

You should now be able to visit the custom endpoint we enabled, http://www.example.com/wp-json/wp/v2/sample_post_type , where you will see the new field ‘sample_post_meta’ and it’s associated data available for us to use. Keep in mind this technique can be used for any post type you have on your site, as well as any associated meta data.

Screenshot:
sample-post-type-api-request-custom-meta-data

If you are not familiar with coding, but need to expose custom post types and it’s associated meta to the REST API, you may want to check out our WP REST API Controller plugin, which allows you to toggle on/off the custom post types and each piece of meta data assigned to those post types – without ever touching code or your theme files.

Wrapping Up

While the examples outlined in this article weren’t earth shattering, you should now have a firm grasp on how you too can expose your post types and associated meta data to the REST API. Maybe you have a better idea of how you can integrate the REST API into your projects, or just wanted to learn more about the inner workings of the REST API. Either way, as we move towards a more fully featured REST API, and it gets included in core, you will really start to see things pick up in popularity and begin to see many many more sites integrating with it, for numerous reasons.

Full Code Block

Below you will find a complete listing of all of the blocks of code outline above. The code below can be copied and pasted directly into your themes functions.php file, where things will just work out of the box. You can use the code below as an example or a starting point for your projects.


<?php } /** * Same the metabox data */ function sample_post_type_metabox_save( $post_id ) { if ( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE ) return; if ( ! isset( $_POST[‘sample_post_type_metabox_nonce’] ) || ! wp_verify_nonce( $_POST[‘sample_post_type_metabox_nonce’], ‘_sample_post_type_metabox_nonce’ ) ) return; if ( ! current_user_can( ‘edit_post’, $post_id ) ) return; if ( isset( $_POST[‘sample_post_meta’] ) ) update_post_meta( $post_id, ‘sample_post_meta’, esc_attr( $_POST[‘sample_post_meta’] ) ); } add_action( ‘save_post’, ‘sample_post_type_metabox_save’ ); /** * Add REST API support to an already registered post type. */ add_action( ‘init’, ‘enable_post_type_rest_support’, 25 ); function enable_post_type_rest_support() { global $wp_post_types; // Populate with post types you want enabled $post_type_array = array( ‘sample_post_type’, ); // Loop over our post type array, and enable the post types foreach ( $post_type_array as $post_type_name ) { if( isset( $wp_post_types[ $post_type_name ] ) ) { $wp_post_types[$post_type_name]->show_in_rest = true; $wp_post_types[$post_type_name]->rest_base = $post_type_name; $wp_post_types[$post_type_name]->rest_controller_class = ‘WP_REST_Posts_Controller’; } } } function slug_get_post_meta_cb( $object, $field_name, $request ) { return get_post_meta( $object[ ‘id’ ], $field_name ); } function slug_update_post_meta_cb( $value, $object, $field_name ) { return update_post_meta( $object[ ‘id’ ], $field_name, $value ); } /** * Register our custom end point to expose our metadata */ add_action( ‘rest_api_init’, function() { register_api_field( ‘sample_post_type’, ‘sample_post_meta’, array( ‘get_callback’ => ‘slug_get_post_meta_cb’, ‘update_callback’ => ‘slug_update_post_meta_cb’, ‘schema’ => null, ) ); });

As always, if you run into any issues or have any questions, feel free to leave us a comment below and we will help out as soon as we can.

I hope you enjoyed this overview of the WP REST API, as well as some of it’s features and code examples. Now go build something cool!

Article Resources

  1. WP REST API v2 Documentation Site
  2. WordPress Plugins Repository
  3. Torque Mag | REST API
  4. WPMU DEV | WordPress REST API
  5. REST API Definition
  6. WP Tavern | REST API Powered Example
  7. Human Made LTD.
  8. Us Two | WP REST API Site Example

Planning for WordCamp US 2015

By Melanie Chongolola-Nestor

November 23, 2015

Hello, Melanie here. If you’ve been keeping up with YIKES’ weekly blog posts, then you should know that I am a neophyte when it comes to Web Development and Design. Thus far I have attended WordCamp Philadelphia in June 2015, and a Girl Develop It Class (Intro to Web Concepts) in September. I feel like they both have been getting me ready for WordCamp US – the biggest WordPress conference in the World, which will be hosted in YIKES’ home town and the city of brotherly love, Philadelphia.

Hopefully you already have your tickets, and are eagerly awaiting for the fourth of December to roll around. I recommend taking a look at the schedule before you show up for registration because there are a lot of classes and lecture offerings. You could just wing it and pop in and out of sessions, but with so many experts and professionals on-hand to answer your questions, you should maximize this opportunity.

The first thing one should note is that the schedule is broken up into tracks and lightening talks. Tracks A and B are full-length talks, and Track C, 10-minute Lightening Talks. You should attend the classes that speak most to the direction you want your learning to take, not which one will allow you to sit next to a friend.

As a novice, these are the courses I am looking forward to taking:

Friday, December 4th

11:05am –  Communities and The Gentle Art of Verbal Self-Defense

Because everyone should know how to shut down internet trolls without losing their cool

11:50am – Themes are for Users

Learn how to choose the right theme to increase the user experience for the visitors to your site

3:25pm – Get It Right The First Time: WordPress Launching Checklist

Self-explanatory, amirite?

5:05pm – Designing For Those Who Matter – Your Users

Another talk about user experience

5:50pm – Publish in 10 Minutes Per Day

Keep your creative juices flowing and your ideas moving forward

6:00pm – What I Learned When My Blog Post Went Viral

Be prepared for big things, even if your site is one of obscure nature.

Saturday, December 5th

9:00am – You can learn a lot from WordPress: Learning by building the Web

Turning your WordPress practice into learning experiences

9:45am – 10 Tips for Clean Code

Clean code is easier to de-bug. Start off right and save time on future fixes.

11:00am – Things you always wanted to know about WordPress (but were afraid to ask)

Self-explanatory, amirite?

2:45pm – Take Care of Each Other: How to Contribute to WordPress Without Writing Code

As a code novice I don’t know the best way to contribute to WordPress, this will tell me how

4:15pm – Explaining Hard Things to Humans: The Principles of Effective Technical Communication

I’m attending this to learn how to best translate tech terms to layman’s terms

The best thing about this schedule is that I will still have time to explore the other offerings of WordCamp US 2015. Opportunity maximized.

Reflections on WordCamp

By Jodie Riccelli

October 26, 2015

The significance of Philadelphia hosting the inaugural year of WordCamp US is not lost on me. I remember my first WordCamp very clearly. It was November of 2011. I was new to my job at YIKES and fairly new to the WordPress community. Eager to learn everything there is to know about WordPress, I awoke early to board the train to Temple University. As I entered the building, Tracy (my boss) was behind the registration desk holding my badge. There were coffee and donuts and … hundreds of people I didn’t know. Armed with my It’s Always Sunny WordCamp t-shirt I just received and a stack of business cards, I proceeded to mingle around the coffee table.

My first thought was that people were so welcoming, but I also noticed that most people had computers with them. Being a less-technical person in a super-technical world has its advantages, preferring to write with a pen and notebook is not always one of them. Now panic stricken because I was without my laptop, I immediately began to think that people would notice I was a newbie. Did I stand out? Did my lack of a messenger bag or a backpack riddled with tiny pins make me look funny? (Pins are a thing in the tech community I have learned, and it’s awesome.)

The sessions were about to start and I got seated at my desk ready to learn. As it turns out, all the preconceived notions in my head were false. I met people of various skill levels throughout the day and many had notebooks just like me. The one common thread throughout the group was the desire to learn. WordPress had brought this seemingly random, diverse group of people together. Here they were growing, learning, and creating websites that now run almost 25% of the internet. I didn’t know it at the time, but that atmosphere would become a safe haven for me.

So here were are, four years later and I’m lucky enough to be part of the organizing committee for WordCamp US. Being accepted into this group of wonderful and brilliant people has been enlightening in so many ways. What stands out for me is that the city of Philadelphia has become part of the WordPress community. It’s part of the organizing team just as much as I am.

The home of democracy is the perfect setting to host an event for a software with democratic principals. When the announcement was made that Philadelphia was selected to host WordCamp US, I was excited and incredibly nervous. What could Philadelphia do to thank the WordPress community for this honor? As time progressed it became a bit clearer. The answer is to give back to the WordPress community. The city of Brotherly Love can easily embrace a group of people that proclaim, “Code is Poetry”.

Philly, get ready because WordCamp US is almost here. You can still purchase tickets and experience the same joy I did at my first WordCamp. Bring a notebook or a laptop and surround yourself with information and knowledge. Thank you for selecting Philly to host WordCamp in 2015 and 2016. We will do you proud, WordPress 🙂

P.S. There are still opportunities to sponsor this historic event! We would love to have you!

Easy Forms for MailChimp Plugin Gets an Upgrade!

By Jodie Riccelli

October 6, 2015

YIKES is excited to launch yikesplugins.com tomorrow — a new site to showcase our awesome WordPress plugins.

With the new site comes a brand new and improved version of our wildly successful Easy Forms for MailChimp plugin. For months we have been working on this new version, and we are excited to release the update tomorrow.

Making the Update

We want our current users to have as smooth a transition as possible so we have created guide to updating:

As always, you can submit support requests for the free version of our plugin to our Github Issue Tracker, and we will respond ASAP.

What’s new in this version?

Completely Rewritten Code

We make note of every support request and feedback message our users send us and have completely rebuilt the codebase to eliminate reoccurring issues. We also had the the code professionally reviewed to ensure it was the highest quality.

“This is certainly a well-coded plugin…it’s in the top 5% – 10% of plugins I’ve seen as far as code goes.”
Justin Tadlock, Co-author Professional WordPress Plugin Development

Brand New Interface

The plugin Admin has been completely redesigned with a streamlined interface.

new-yikes-mailchimp-plugin-interface

New Knowledge Base

We have created a Knowledge Base full of articles with step-by-step guides on plugin installation, use, settings and developer documentation.

New Add-Ons

We built fabulous free and premium add-ons to extend the base functionality of Easy Forms for MailChimp. Paid add-ons also come with premium support.

One add-on we know you’ll love is the Form Customizer. With it you can completely customize the look of your forms without needing to know any code.

Watch this video demo if it in action.

Visit our new plugins website to see all the free and premium add-ons available.

We are excited to release these and more great plugins in the future.

WordPress version 4.3 – “Billie”

By Tracy Levesque

August 18, 2015

WordPress Version 4.3 came out today, and the YIKES crew is proud to have made contributions to this release.

Language Translation

Carlos is a member of the WordPress Polyglots team and an active contributor and editor of Spanish (Mexico). He translated and approved hundreds of strings for WordPress 4.3.

Dashicons

I designed a couple new Dashicons for the WordPress admin – “Rotate” and “Unlock” to go along with the Lock icon.

dashicons-4.3

Admin UX

At WordCamp Philly we were lucky to have lead developer, Helen Hou-Sandí, in attendance at our contributor day. I was interested in the work she was doing regarding cleaning up the WordPress Admin and was able to learn about tasks with which I could help. I got some handy SVN tips from Helen as well.

Admin forms on mobile

The contribution I am most proud of is improving the error messaging on forms.

Before

Add New User before

After

Add New User after

In addition to looking nicer, the use of the alert icon doesn’t just rely on color to convey an error, making it better for accessibility.

I have really enjoyed participating in the WordPress #Design Slack channel. I love seeing how much thought people put into every design decision that is made.

Learn about all the great new features in 4.3.

Our WordPress Monitoring Service Just Got Better

By Mia Levesque

July 9, 2015

Previously, our WordPress Monitoring Service included WordPress Core updates within 24-48 hours of release and once per month plugin updates. As of July 1, 2015 both WordPress Core and Plugin updates will be made within 24 hours of release. Also, if an update causes an issue for a monitored site, we will fix it.

Our YIKES WordPress Monitoring plugin, only available to our Monitoring clients, notifies us on Slack (our real-time communication tool) the minute a plugin needs updating on a site.

As WordPress experts, we keep tabs on and immediately address security issues.

Here are some examples of security issues we took care of while our monitoring clients relaxed.

  • Object Injection Vulnerability in WooCommerce
  • Critical Persistent XSS 0day in WordPress
  • File upload Vulnerability in Gravity Forms
  • Persistent XSS in WP-Super-Cache
  • Blind SQL Injection Vulnerability in Yoast SEO

If a plugin or WordPress itself has a critical security patch, we will know and will apply it immediately.

Pricing

$50/month per site or $500/year ($100 discount) per site.

If you’re not already on our monitoring plan, contact us to see if your site qualifies

WordCamp Philly 2015

By Mia Levesque

June 13, 2015

volunteering WordCamp Philly 2015After a busy month of organizing this year’s WordCamp Philly (and building the website), the whole YIKES team is enjoying the sold-out conference this weekend. We are volunteering, teaching and learning.

If you are attending, share your experience on Twitter using #wcphilly
@WordCampPhily and @yikesinc.