Skip to content

Instantly share code, notes, and snippets.

@monecchi
Last active June 7, 2016 17:42
Show Gist options
  • Save monecchi/01a06773be8c21525015209b33d53ac4 to your computer and use it in GitHub Desktop.
Save monecchi/01a06773be8c21525015209b33d53ac4 to your computer and use it in GitHub Desktop.
Get Custom Post Types Using the WP API V2
<?php
/*
* Easy! Using the example of a custom post type called ‘the_event’,
* you’d just put the following into your functions.php file (or plugin).
* Credits go to author: https://bay-a.co.uk/wordpress-tips/wp-api-v2-tips/
*/
add_action( 'init', 'add_events_to_json_api', 30 );
function add_events_to_json_api(){
global $wp_post_types;
$wp_post_types['the_event']->show_in_rest = true;
$wp_post_types['the_event']->rest_base = 'the_event';
$wp_post_types['the_event']->rest_controller_class = 'WP_REST_Posts_Controller';
}
// You will now be able to visit "http://yoursite.com/wp-json/wp/v2/the_event/" and see the post data in json format
// Bonus:
// You’re able to get all custom post types dynamically into an array like so:
$types = get_post_types(('public' => true,'_builtin' => false));
// And then loop through them, and for each one, use the code I’ve provided further up above to register them with WP-API.
?>
<?php
/*
* GET CUSTOM POST TYPE META DATA VIA WP-API V2
*/
// Again, we’re using the the_event custom post type, and we’re getting 3 pieces of meta: _the_event_start, _the_event_end, and _the_event_location.
// Just use this code below, replacing all instances of the_event with your custom post type – including in the filter name.
add_filter( 'rest_prepare_the_event', 'add_meta_to_json', 10, 3 );
function add_meta_to_json($data, $post, $request){
$response_data = $data->get_data();
if ( $request['context'] !== 'view' || is_wp_error( $data ) ) {
return $data;
}
$start = get_post_meta( $post->ID, '_the_event_start', true );
if(empty($start)){
$start = '';
}
$end = get_post_meta( $post->ID, '_the_event_end', true );
if(empty($end)){
$end = '';
}
$location = get_post_meta( $post->ID, '_the_event_location', true );
if(empty($location)){
$location = '';
}
if($post->post_type == 'the_event'){
$response_data['event_meta'] = array(
'start' => $start,
'end' => $end,
'location' => $location,
);
}
$data->set_data( $response_data );
return $data;
}
// More on https://bay-a.co.uk/wordpress-tips/wp-api-v2-tips/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment