Skip to content

Instantly share code, notes, and snippets.

@carlodaniele
Created August 17, 2016 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlodaniele/78ba91c7f40c5f8e3b8d070df2f2eb10 to your computer and use it in GitHub Desktop.
Save carlodaniele/78ba91c7f40c5f8e3b8d070df2f2eb10 to your computer and use it in GitHub Desktop.
Adds latitude and longitude post meta field values to REST API response.
<?php
/**
* @package REST_API_my_meta_fields
* @version 1.0
*/
/*
Plugin Name: REST API my meta fields
Plugin URI: http://wordpress.org/extend/plugins/#
Description: This is an example plugin
Author: Carlo Daniele
Version: 1.0
Author URI: http://carlodaniele.it/en/
*/
/**
* Register custom REST API fields
*
* @link http://v2.wp-api.org/extending/modifying/
*/
function REST_API_register_my_fields(){
register_rest_field( 'post',
'latitude',
array(
'get_callback' => 'get_my_field_cb',
'update_callback' => null,
'schema' => null
)
);
register_rest_field( 'post',
'longitude',
array(
'get_callback' => 'get_my_field_cb',
'update_callback' => null,
'schema' => null
)
);
}
add_action( 'rest_api_init', 'REST_API_register_my_fields');
/**
* Get the value of a REST API custom field
*
* @param array $object Details of current post.
* @param string $field_name Name of field.
* @param WP_REST_Request $request Current request
*
* @return mixed
*/
function get_my_field_cb( $post, $field_name, $request ){
return get_post_meta( $post['id'], $field_name );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment