Add Meta in Rest API

Advertisement

Add post meta in post (custom post type) endpoint with Rest API.

Todo: Todo:

  • Change post-type with your post type slug.
  • Change prefix-meta-key with your post meta key which you want to include in Rest API Response.

Top ↑

Output: Output:

Visit https://<mysite>/wp-json/wp/v2/<post-type>/ it show the stored data from meta key  prefix-meta-key in the Rest API response.

Top ↑

Code: Code:


<?php
/**
* Add post meta in post (custom post type) endpoint with rest api.
*
* @todo Change `post-type` with your post type slug.
* @todo Change `prefix-meta-key` with your post meta key which you want to include in Rest API Response.
*
* @package Prefix
* @since 1.0.0
*/
if ( ! class_exists( 'Prefix_Rest_API' ) ) :
/**
* Prefix Rest API
*
* @since 1.0.0
*/
class Prefix_Rest_API {
/**
* Instance
*
* @access private
* @var object Class object.
* @since 1.0.0
*/
private static $instance;
/**
* API Request Start Time
*
* @access private
* @var string Start time.
* @since 1.0.0
*/
private static $start_time;
/**
* Initiator
*
* @since 1.0.0
* @return object initialized object of class.
*/
public static function get_instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Constructor
*
* @since 1.0.0
*/
public function __construct()
{
add_action( 'rest_api_init', array( $this, 'meta_in_rest' ) );
}
/**
* Add Extra Fields in Rest
*
* @since 1.0.0
*
* @return void
*/
public function meta_in_rest() {
// Start logging how long the request takes for logging.
self::$start_time = microtime( true );
register_rest_field(
'post-type',
'prefix-meta-key',
array(
'get_callback' => array( $this, 'get_post_meta' ),
'schema' => null,
)
);
// Request Time.
register_rest_field(
'post-type',
'request_time',
array(
'get_callback' => array( $this, 'get_api_request_time' ),
'schema' => null,
)
);
}
/**
* Get Site URL
*
* @since 1.0.0
*
* @param string $object Rest Object.
* @param string $field_name Rest Field.
* @param array $request Rest Request.
* @return string Post Meta.
*/
public function get_post_meta( $object = '', $field_name = '', $request = array() )
{
return get_post_meta( $object['id'], $field_name, true );
}
/**
* Set API request Time
*
* @since 1.0.0
* @param string $object Rest Object.
* @param string $field_name Rest Field.
* @param array $request Rest Request.
* @return mixed Null or Site Featured Image.
*/
public function get_api_request_time( $object = '', $field_name = '', $request = array() )
{
// End time of logging.
$end_time = microtime( true );
return ( $end_time – self::$start_time );
}
}
/**
* Kicking this off by calling 'get_instance()' method
*/
Prefix_Rest_API::get_instance();
endif;

 

Leave a Reply