Skip to content

Instantly share code, notes, and snippets.

@dr5hn
Last active September 24, 2017 14:13
Show Gist options
  • Save dr5hn/e3e9c0af2a0ebe5f76850a5c869c078f to your computer and use it in GitHub Desktop.
Save dr5hn/e3e9c0af2a0ebe5f76850a5c869c078f to your computer and use it in GitHub Desktop.
Registering Menu, Custom Post Types, Custom Fields & Custom Plugins to REST API in Wordpress
<?php
//Registering Menu Items to REST API (API URL : http://website.com/wp-json/menu/)
function get_menu() {
# Change 'hamburger' to your own navigation slug.
return wp_get_nav_menu_items('hamburger');
}
add_action( 'rest_api_init', function () {
register_rest_route( 'spirit', '/menu', array(
'methods' => 'GET',
'callback' => 'get_menu',
) );
} );
/**
* Add REST API support to an already registered post type. (Custom Plugins or Custom Post Type)
* API URL : http://www.website.com/wp-json/wp/v2/<post_type>
*/
add_action( 'init', 'cp_recipe_rest_support', 25);
function cp_recipe_rest_support() {
global $wp_post_types;
//be sure to set this to the name of your post type!
$post_type_name = 'cp_recipe';
if( isset( $wp_post_types[ $post_type_name ] ) ) {
$wp_post_types[$post_type_name]->show_in_rest = true;
$wp_post_types[$post_type_name]->rest_base = $post_type_name;
$wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
}
}
//Registering Custom Fields of (Custom Post Type or Custom Plugin) to Rest API
//Adding Custom Input Fields
add_action('rest_api_init', 'slug_register_short_desc');
function slug_register_short_desc() {
register_rest_field('cp_recipe','_cp_recipe_short_description',
array(
'get_callback' => 'slug_get_short_desc',
'update_callback' => null,
'schema' => null
)
);
}
function slug_get_short_desc($object,$field_name,$request) {
return get_post_meta($object['id'],$field_name,true);
}
//Addding Featured Image (Extracting URL and Adding it to REST API)
add_action('rest_api_init', 'slug_register_featured_image');
function slug_register_featured_image() {
register_rest_field('cp_recipe','featured_image',
array(
'get_callback' => 'slug_get_featured_image',
'schema' => null
)
);
}
function slug_get_featured_image($object,$field_name,$request) {
// Only proceed if the post has a featured image.
if ( ! empty( $object['featured_media'] ) ) {
$image_id = (int)$object['featured_media'];
} elseif ( ! empty( $object['featured_image'] ) ) {
// This was added for backwards compatibility with < WP REST API v2 Beta 11.
$image_id = (int)$object['featured_image'];
} else {
return '';
}
$image = get_post( $image_id );
if ( ! $image ) {
return '';
}
$featured_image = wp_get_attachment_url( $image_id );
return apply_filters( 'slug_get_featured_image', $featured_image, $image_id );
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment