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

How to integrate Google Maps into your site

By Evan Herman

December 19, 2015

Overview

At one point or another you’ve probably wanted to add interactive Google maps to your site. Whether it be for directions to your office, the location of an event or to display locations in the area, such as restaurants. Whatever the case may be, I’m going to walk you through the process of adding a Google Map to your site, the correct way. The WordPress way. This should be helpful to anyone building out custom themes for clients or for your own personal use.

Getting Started

Before we get started, it may help to get a better understanding of what we’ll actually be doing – and the steps that need to be taken to achieve the look we’re after. We are going to be generating the HTML markup and enqueueing the necessary JavaScript files required to initialize a map on your site. We’ll walk through each step together to get a better understanding of how to properly load the files on your WordPress site.

There are going to be five main sections to this tutorial, each step building on top of the previous one. In the first section, we’ll initialize a simple Google Map. In the second section, we’ll add a visual indicator to the map on our location. In the third section, we’ll take it one step further and display an information box above the map marker when it’s clicked. In the fourth section, we’re going to populate a single map with multiple markers. And finally in the fifth section, we’ll wrap up our tutorial with how to use our own custom map markers, instead of the default one provided by google. In a bonus section at the end of our tutorial, we’ll walk through how to use Snazzy Maps to add custom styles to our maps and give them a bit more personality.

Let’s begin!

Section 1) Initializing a Simple Google Map

Note: This is the longest section, as it requires us to load the required JavaScript files and place the necessary HTML on our site. Once this section is complete, the majority of changes to our Google Map will be done in a single JavaScript file.

Step 1: Add the HTML

map-html-in-widget

The first thing we’ll need to do is add an HTML element on the page that will be used to display our map in. This is the element that our JavaScript file is going to look for, and initialize the Google Map on. The easiest way to do this, is to add the following to a ‘Text’ widget. This way our map can be displayed in a sidebar, the footer or any other widgetized area of our site. But the following HTML code can also be used in posts, pages or in theme template files.

Ideally you’ll want to add the height declaration into the style.css file of your active theme, but for brevity I added the styles inline on our map element.

Map HTML Markup
<div id="map" style="height:350px;"></div>

Step 2: Load the JavaScript file

To begin, we’ll need to enqueue the required JavaScript file from the Google CDN. When we enqueue a file in WordPress, we’re telling WordPress to load the file on our site, in the appropriate location (header or footer).

Depending on where the map will be displayed on your site, you can alter the follow function to your needs with conditional statements. In this tutorial, I’m going to assume that the map will be displayed in the footer of your site, thus we’ll have to load the required JavaScript file on every page of our site.

The following function can be added to the bottom of the functions.php file of your active theme.

Once added, go ahead and save the functions.php file.

Step 3: Create a custom JavaScript File

Now we’ll need to create a JavaScript file which will house all of our Google Maps settings. This can reside in the root of your theme inside of a ‘js’ directory. (eg: wp-content/themes/theme-name/js/).

Remember to give this file an appropriate name so in future we know what this script does. I’m going to name it google-maps-init.js, and place it in the directory path mentioned above.

Inside of the new JavaScript file, google-maps-init.js, we’ll first just write an alert. This way when the file gets loaded in the browser, an alert will trigger, and we’ll know that our JavaScript file has loaded properly. Add the following to your JavaScript file, and save it.

Now we’ll need to enqueue the JavaScript file we just created after our Google Maps script, from the previous step. Building onto the function above, you’ll want to enqueue the JavaScript file we just created like so:

You’ll notice that in the new line of our function, we’re passing in a third parameter, an array. The third parameter let’s WordPress know that we want to load google-maps-init after the google-maps-api script has fully loaded. This ensure that when we go to initialize the map, the Google Maps JavaScript file exists and all of the functions we’ll need are there and available to use.

Once you’ve updated the the function inside of functions.php, go ahead and refresh your site. You should see an alert box popup stating ‘google-maps-init.js is ready’. Now we’re ready to initialize the map.

Step 4: Initialize the Map

Now that we’ve generated the necessary HTML on our site, and loaded the required JavaScript files in the order we need – we’re ready to initialize the map.

Inside of the custom JavaScript file, google-maps-init.js, we can delete the alert since we now know our file is loaded properly on our site. After deleting the alert, we can now add the following to our .js file:

The first thing you’ll notice is that we’re passing in Latitude and Longitude values to the center argument, which will be our location. Google Maps uses the latitude and longitude values to pin point a location on a map. You may be wondering ‘How do I find those values for my location?‘. Well, there are a number of ways, but the easiest and quickest that I’ve found is using the Latitude and Longitude lookup tool.

You can quickly find locations by address and copy and paste the values into the JavaScript function above, inside of our google-maps-init.js file.

You’ll also notice the zoom argument passed into the initialization function. This allows us to set a default zoom value. The possible values range from 0-18, 0 being completely zoomed out and 18 being zoomed in as close as possible.

You can now save the file, and refresh your site. You should now be seeing a fully initialized Map of your location in the sidebar or footer of your site (depending on where you added the HTML from step 1).

Section 2) Adding a Marker to Our Map

Now that we have a working Google Map on our site, the next step most people will want to take is to add a marker to the map. The marker is a simple visual indicator, representing our location. But we can add additional features to the marker, so that when it’s clicked – details about the location display in a small window above the marker. Let’s go ahead and do that. We’ll be working inside google-maps-init.js, created in the section above. First we’ll add our map marker. Our new google-maps-init.js will look like:

Our new section is now prefaced with the comment ‘Map Marker’. The first argument for our marker is the position of the marker. This is going to be the exact same value as the center argument in our Google Maps init function above. This ensures that our marker displays on top of our set location. The next parameter, map, we simply pass in the map object created above. This allows us to specify which map on our site we want the marker displayed on. For this tutorial, we only have one map so it’s pretty straight forward. The title argument is the text that displays on marker hover. This is the same as the title attribute on an anchor tag. Finally, I’ve added an animation argument. This is optional, but add’s a nice subtle touch to the map. When the map is generated and displays, the map marker will animate so it looks like it’s ‘dropping’ onto the map.

After you’ve made alterations to the map marker for your specific implementation, you can save the google-maps-init.js file and refresh your site. You should now see the map marker displayed on your map. If you hover on the marker for a second or two, you’ll see the text in our title display.

Section 3) Adding an Info Box Above the Marker

In this section we’re going to add a small popup above the marker with some additional details about our location. We’ll alter google-maps-init.js to reflect the following:

This is the YIKES Inc. main offices, located in the beautiful Fishtown section of Philadelphia, PA.

‘, }); // Map Marker var marker = new google.maps.Marker({ position: {lat: 39.968887, lng: -75.133297}, map: map, title: ‘YIKES Inc.’, animation: google.maps.Animation.DROP }); // Add event listener for the Info Box marker.addListener(‘click’, function() { infowindow.open(map, marker); }); });

We’ve gone ahead and added two additional sections to our JavaScript file. The first is commented with ‘Info Box Content’, and the second with ‘Add event listener…’. We first define a new variable called infowindow, which defines an InfoWindow object on our Google Map. The content parameter is the content of the InfoWindow. This section accepts standard HTML markup to display and style the content as needed. Finally we add an event listener to our map marker, so that when it’s clicked our new info window displays in a nice container above our map marker.

Go ahead and make the updates to your google-maps-init.js JavaScript file, save it and refresh the site to view our changes.

Section 4) Displaying Multiple Locations on a Single Map

Displaying multiple locations on a single map is quite similar to what we’ve written above for a single location. The only difference is that instead of passing in a single location, we’ll now define multiple locations in a single array and then loop over them to properly initialize them and display them on our map.

First let’s define our multi-location array:

You’ll notice that we’ve setup a multi-dimensional array, where each entry in the array is our location with additional location details.

Example:

  • fishtown_attractions[0][0] – Joes Cheesteak (location name)
  • fishtown_attractions[0][2] – The best cheesesteaks this side of Market Street. Do not miss out on this instant classic! (location description)
  • fishtown_attractions[1][0] – Barcade
  • fishtown_attractions[1][2] – 39.967452 (equal to our longitude for this location)
  • Once we have an array of locations to work with, we’ll need to simply loop over each location, and add it to our map. For multiple map markers on a single instance of a map, your JavaScript file should be similar to:

    ‘ + fishtown_attractions[i][1] + ‘

    ‘ ); infowindow.open(map, marker); } })(marker, i)); } });

    In the next section we’ll swap out the default map markers and define our own custom markers to use in the map. For each location type, we’ll use a different map marker to help visually differentiate between them all.

    Section 5) Using Custom Map Markers

    In the previous section we defined the locations on our map, initialized our map, setup map markers and a small info box above each location. In this section we’re going to wrap up the tutorial by defining our own custom icons for each location on the map. This is going to help our users differentiate between all of the locations by type. You can also take this one step further and create a visual ‘key’ for your users to follow – but in this tutorial we’re going to keep it basic.

    The first thing you’ll want to do is decide what icons you’ll be using for each location. Since I’ve only defined 4 locations on the map, I’m going to gather 4 different icons.

    These are the icons that I’ve chosen to use, compiled into a single image file (to show you which icons I’m using). You’ll want to leave your map icons in separate image files, which will make working with them easier.

    icon-sheet

    You’ll want to upload your images somewhere on your site. I’ve gone ahead and created an /images/ folder inside of my theme root, alongside the /js/ directory we created in an earlier section. Inside of the /images/ directory, I’ve gone ahead and uploaded the four icons displayed above as four separate images:

  • joes-icon.png
  • barcade-icon.png
  • tree-icon.png
  • bike-icon.png
  • Note: I’ve set all of my icons to 50px wide, so they appear uniform.

    After you’ve uploaded your icons to the root of your theme (or another location that you’ve specified), we’ll want to go ahead and add one more item to the end of our fishtown_attractions array. This last item will be the name of the associated icon for the given located, and will be used to display the appropriate icon on the correct location.

    Now your entire JavaScript initialization file should look like the following:

    ‘ + fishtown_attractions[i][1] + ‘

    ‘ ); infowindow.open(map, marker); } })(marker, i)); } });

    Bonus Section) Custom Google Map Styles Using SnazzyMaps.com

    Finally, we’ll wrap up this tutorial with a small tutorial on styling your maps. The quickest and most efficient way to style maps, that I’ve personally come across is a service called Snazzy Maps. Snazzy Maps is a crowd sourced site of pre-defined styles for your Google Maps. I’ve found this site to be the best because it’s going to save you a tremendous amount of time meticulously tweaking and adjusting styles. You can sort by relevance, popularity, date of upload or name, filter by tags or even filter the map styles by color.

    Once on the site, you can browse around and preview what the styles will look like when applied to your map. I generally filter by popularity to check some of the nicer styles. When you’ve found a set of map styles that you would like to use, you can click on the style to bring you into the individual style listing page where you’ll find the code we need to add these styles to our map.

    You’ll notice that the styles are defined and compiled into a JavaScript array, which is exactly what the Google Maps initialization script expects.

    As an example, let’s say that you really liked the Flat Map with Labels map styles, and want to apply them to your map. All you need to do is click ‘Copy’ in the top right hand corner of the JavaScript Style Array window. Once copied, you’ll simply need to pass them in via a styles parameter.

    Looking at the entire script as a whole, you should now have something similar to:

    ‘ + fishtown_attractions[i][1] + ‘

    ‘ ); infowindow.open(map_6, marker); } })(marker, i)); }

    And that’s all there is to it! If the styles we just added don’t fit into the look and feel of your site, you can easily select another set of styles on Snazzy Maps and quickly swap out the JavaScript array in your initialization script to tweak the styles as needed.

    Wrapping Up

    Now that we’ve gone through all the motions of setting up a Google Map in your project – I’m hoping that you now have a stronger understanding of how to utilize Google Maps to it’s full potential in your projects. My hope is that this once intimidating idea of working with Google maps, make a whole lot more sense now. That you can walk away from this tutorial (or even reference it in future) and start integrating awesome and powerful maps into your projects.

    Now go out there and Wow your clients!