Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Created May 30, 2018 20:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wpscholar/5436f13f565e1573f94f420a6a5a68a6 to your computer and use it in GitHub Desktop.
Save wpscholar/5436f13f565e1573f94f420a6a5a68a6 to your computer and use it in GitHub Desktop.
Plugin for creating a post type with a custom API that reflects Schema.org data structures
<?php
/*
* Plugin Name: Schema API
* Plugin URI:
* Description:
* Version: 0.1.0
* Author: Micah Wood
* Author URI: https://wpscholar.com
* License: GPL2
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain:
*/
add_action( 'init', function () {
register_post_type( 'person', [
'public' => true,
'labels' => [
'name' => 'People',
'singular_name' => 'Person',
],
'supports' => [
'title',
'editor',
'custom-fields',
'postal-address',
],
] );
} );
add_action( 'rest_api_init', function () {
register_rest_route( 'schema/v1', '/people', [
'methods' => 'GET',
'callback' => function ( WP_REST_Request $request ) {
$query = new WP_Query( [
'post_type' => 'person',
] );
$posts = (array) $query->posts;
return rest_ensure_response( array_map( 'transformPost', $posts ) );
},
'args' => array(),
] );
register_rest_route( 'schema/v1', '/person/(?P<id>\d+)', [
'methods' => 'GET',
'callback' => function ( WP_REST_Request $request ) {
return rest_ensure_response( transformPost( get_post( $request->get_param( 'id' ) ) ) );
},
'args' => array(
'id' => array(
'validate_callback' => function ( $param, $request, $key ) {
if ( ! is_numeric( $param ) ) {
return new WP_Error( 'bad_post_id', __( 'Invalid post ID format. Please pass an integer.' ), array( 'status' => 400 ) );
}
$post_id = (int) $param;
if ( false === get_post_status( $post_id ) || 'person' !== get_post_type( $post_id ) ) {
return new WP_Error( 'bad_post_id', __( 'Invalid post ID.' ), array( 'status' => 400 ) );
}
return true;
}
),
),
] );
} );
function transformPost( WP_Post $post ) {
$obj = new stdClass();
$obj->givenName = $post->first_name;
$obj->familyName = $post->last_name;
$obj->postalAddress = extractAddress( $post );
return $obj;
}
function extractAddress( WP_Post $post ) {
return (object) array_filter( [
'addressCountry' => $post->addressCountry,
'addressLocality' => $post->addressLocality,
'addressRegion' => $post->addressRegion,
'postOfficeBoxNumber' => $post->postOfficeBoxNumber,
'postalCode' => $post->postalCode,
'streetAddress' => $post->streetAddress,
] );
}
/*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment