WP REST API Custom Fields to Google Maps


Manuel, the young shrimp-picker, five years old, and a mountain of child-labor oyster shells behind him. He worked last year. Understands not a word of English. Dunbar, Lopez, Dukate Company. Location: Biloxi, Mississippi. (LOC) flickr photo by The Library of Congress shared with no copyright restriction (Flickr Commons) 1

I had a site we used for the Great VCU Bike Race course that’s been sitting around. I knew it had lat/lng data for lots of urban bicycle related posts. My goal was to get it into Google Maps via the REST API.

Get Custom Field in JSON

By default you won’t see custom field data in your JSON endpoints. There are some plugins to make that happen but I wanted to take a stab at doing it myself. Given the documentation, it was pretty trivial.2 The code below in a plugin or the function.php file would make the lat_long custom field show up in the post JSON.

add_action( 'rest_api_init', function() {
    register_rest_field( 'post', 'lat_long', array(
        'get_callback' => function( $post_arr ) {
            $post_obj = get_post( $post_arr['id'] ); 
            return (string) $post_obj->lat_long;
        },
        'update_callback' => function( $lat_long, $post_obj ) {
            $ret = wp_update_post( array(
                'post_ID'    => $post_obj->post_ID,
                'post_lat_long' => $lat_long
            ) );
            if ( false === $ret ) {
                return new WP_Error( 'rest_post_lat_long_failed', __( 'Failed to update field lat_long.' ), array( 'status' => 500 ) );
            }
            return true;
        },
        'schema' => array(
            'description' => __( 'Custom field lat_long.' ),
            'type'        => 'string'
        ),
    ) );
} );

Using this URL, I can get the 30 most recent posts.3

https://rampages.us/bicycleurbanism2015/wp-json/wp/v2/posts?_embed&per_page=30

Some Map Stuff

Google wants lat/lng separate but it’s coming in as one item split by a comma. These little functions split it up nicely. In javascript, split breaks up a string by the defined element (comma in this case) and returns the pieces as an array. Since I’ll get two pieces every time and they are always in the same order, I can just define that in the return.4

function cleanLat(input){
  var lat = input.split(',');
  return lat[0];
}

function cleanLng(input){
  var lng = input.split(',');
  return lng[1];
}

I changed the marker icons to green with this. It seems like an awkward way to do it but none of my other paths worked. You could also replace the URL with a path to your own image . . . which is a scenario where this would make more sense to me.

      marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png'); //green seemed more positive

Anyway, now we’ve got a nice functional map with the content of the WordPress posts showing up inside the marker info windows.

See the Pen WP JSON API V2 Custom Field to Google Maps by Tom (@twwoodward) on CodePen.


1 While I don’t want our five year olds being put to work, I can’t help but think we treat them terribly in the other direction. Anyway, on with the show/boring tutorial-ish thing . . .

2 That means I didn’t white screen the test site or get critical errors on my first attempt.

3 It’s important to do 30 instead of 10 or you might spend a period of time trying to figure out why only one marker shows up. (Hint: it’s because only one of the first 10 items has lat/lng data.)

4 It might be better to have only one function and then do the element selection on the return value . . . I don’t know. I make up 98% of this stuff and then learn something new the next day that further blows my mind.