Você está na página 1de 2

/**

* Add REST API support to an already registered post type


* http://v2.wp-api.org/extending/custom-content-types/
* Access this post type at yoursite.com/wp-json/wp/v2/post_type_name
*/
add_action( 'init', 'appp_post_type_rest_support', 999 );

function appp_post_type_rest_support() {

global $wp_post_types;

//be sure to set this to the name of your post type!


$post_type_name = 'listing';
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';
}

/**
* Add featured image urls to post response
* Default is to show media ID, but then you have to do another http request to get
the image for an app. This allows you to just use the url.
* Sample usage would be post.featured_image_urls.thumbnail
*/
add_action( 'rest_api_init', 'appp_add_featured_urls' );
function appp_add_featured_urls() {
register_rest_field( array( 'post', 'listing' ),
'featured_media',
array(
'get_callback' => 'appp_featured_images',
'update_callback' => null,
'schema' => null,
)
);
}

function appp_featured_images( $post ) {

$featured_id = get_post_thumbnail_id( $post['id'] );

$sizes = wp_get_attachment_metadata( $featured_id );

$size_data = new stdClass();

if ( ! empty( $sizes['sizes'] ) ) {

foreach ( $sizes['sizes'] as $key => $size ) {


// Use the same method image_downsize() does
$image_src = wp_get_attachment_image_src( $featured_id, $key );

if ( ! $image_src ) {
continue;
}

$size_data->$key = $image_src[0];
}

return $size_data;

}
/**************************************************/

/**
* Add post meta to a response
* http://v2.wp-api.org/extending/modifying/
* This example adds price to a woocommerce product. Meta key is _price, and
corresponding api field will also be _price.
*/
add_action( 'rest_api_init', 'appp_register_post_meta' );
function appp_register_post_meta() {
register_rest_field( 'listing', // any post type registered with API
'author', // this needs to match meta key
array(
'get_callback' => 'appp_get_meta',
'update_callback' => null,
'schema' => null,
)
);
}

/**
* Get the value of a meta field 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 appp_get_meta( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], $field_name, true );
}

Você também pode gostar