[API] viết REST Response Modifier register_rest_field Full (ok)

<?php
/**
 * Plugin Name: REST Response Modifier
 * Description: A very simple plugin for development and testing purpose to modify the response of the REST API plugin.
 * Author: Bilal Shahid
 * Author URI: http://imbilal.com
 */
add_action('rest_api_init', 'bs_add_custom_rest_fields');

/**
 * Function for registering custom fields
 */
function bs_add_custom_rest_fields() {
  // schema for the bs_author_name field
  $bs_author_name_schema = array(
    'description' => 'Name of the post author',
    'type'        => 'string',
    'context'     => array('view'),
  );

  // registering the bs_author_name field
  register_rest_field(
    'post',
    'bs_author_name',
    array(
      'get_callback'    => 'bs_get_author_name',
      'update_callback' => null,
      'schema'          => $bs_author_name_schema,
    )
  );

  // schema for bs_post_views field
  $bs_post_views_schema = array(
    'description' => 'Post views count',
    'type'        => 'integer',
    'context'     => array('view', 'edit'),
  );

  // registering the bs_post_views field
  register_rest_field(
    'post',
    'bs_post_views',
    array(
      'get_callback'    => 'bs_get_post_views',
      'update_callback' => 'bs_update_post_views',
      'schema'          => $bs_post_views_schema,
    )
  );
}

/**
 * Callback for retrieving author name
 * @param  array            $object         The current post object
 * @param  string           $field_name     The name of the field
 * @param  WP_REST_request  $request        The current request
 * @return string                           The name of the author
 */
function bs_get_author_name($object, $field_name, $request) {
  return get_the_author_meta('display_name', $object['author']);
}

/**
 * Callback for retrieving post views count
 * @param  array            $object         The current post object
 * @param  string           $field_name     The name of the field
 * @param  WP_REST_request  $request        The current request
 * @return integer                          Post views count
 */
function bs_get_post_views($object, $field_name, $request) {
  return (int) get_post_meta($object['id'], $field_name, true);
}
/**
 * Callback for updating post views count
 * @param  mixed    $value          Post views count
 * @param  object   $object         The object from the response
 * @param  string   $field_name     Name of the current field
 * @return bool|int
 */
function bs_update_post_views($value, $object, $field_name) {
  if (!$value || !is_numeric($value)) {
    return;
  }
  return update_post_meta($object->ID, $field_name, (int) $value);
}

Ví dụ 2: Lấy ở https://upnrunn.com/blog/2018/02/extend-wp-rest-api-custom-plugin-part-1/

C:\xampp\htdocs\api\wp-content\plugins\rest\rest-api-tutorial.php

<?php  
	/**
 * Plugin Name: Rest Api Tutorial
 * Description: How to extent WP RSET api from your custom plugin.
 * Version: 1.0.0
 * Author: upnrunn
 * Author URI: https://upnrunn.com/
 * License: GPL2+
 *
 * @package Rest_Api_Tutorial
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

// Define constants.
define( 'REST_API_TUTORIAL_PLUGIN_VERSION', '1.0.0' );
define( 'REST_API_TUTORIAL_PLUGIN_DIR', untrailingslashit( plugin_dir_path( __FILE__ ) ) );

// Include the main class.
require plugin_dir_path( __FILE__ ) . 'includes/class-rest-api-tutorial.php';

// Main instance of plugin.
function rest_tutorial() {
    return Rest_Api_Tutorial::get_instance();
}

// Global for backwards compatibility.
$GLOBALS['rest_tutorial'] = rest_tutorial();
?>

C:\xampp\htdocs\api\wp-content\plugins\rest\includes\class-rest-api-tutorial.php

<?php
/**
 * Main class.
 *
 * @package Rest_Api_Tutorial
 */
class Rest_Api_Tutorial {
  /**
   * Returns the instance.
   */
  public static function get_instance() {
    static $instance = null;
    if (is_null($instance)) {
      $instance = new self();
    }
    return $instance;
  }
  /**
   * Constructor method.
   */
  private function __construct() {
    $this->includes();
  }
  // Includes
  public function includes() {
    include_once REST_API_TUTORIAL_PLUGIN_DIR . '/parts/part-2/method-1.php';
    include_once REST_API_TUTORIAL_PLUGIN_DIR . '/parts/part-2/method-2.php';
  }
}

C:\xampp\htdocs\api\wp-content\plugins\rest\parts\part-2\method-1.php

<?php
add_action('rest_api_init', 'register_post_fields');
// Register post fields.
function register_post_fields() {
  register_rest_field('post', 'post_views', array(
    'get_callback'    => 'get_post_views',
    'update_callback' => 'update_post_views',
    'schema'          => array(
      'description' => __('Post views.'),
      'type'        => 'integer',
    ),
  ));
}
// Get post views
function get_post_views($post_obj) {
  $post_id = $post_obj['id'];
  return get_post_meta($post_id, 'post_views', true);
}
// Update post views
function update_post_views($value, $post, $key) {
  $post_id = update_post_meta($post->ID, $key, $value);
  if (false === $post_id) {
    return new WP_Error(
      'rest_post_views_failed',
      __('Failed to update post views.'),
      array('status' => 500)
    );
  }
  return true;
}
?>

C:\xampp\htdocs\api\wp-content\plugins\rest\parts\part-2\method-2.php

<?php
// Register post meta
$object_type = 'post';
$args        = array(
  'type'         => 'string',
  'description'  => 'A meta key associated with post views.',
  'single'       => true,
  'show_in_rest' => true,
);
register_meta($object_type, 'post_views', $args);
?>

Last updated