Created
May 30, 2018 20:25
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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