Skip to content

Instantly share code, notes, and snippets.

@maheshwaghmare
Created December 10, 2019 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maheshwaghmare/a2f760ebb2ec5fb593bb76eda8c831cd to your computer and use it in GitHub Desktop.
Save maheshwaghmare/a2f760ebb2ec5fb593bb76eda8c831cd to your computer and use it in GitHub Desktop.
WordPress Rest API Boilerplate
<?php
/**
* Prefix Rest API
*
* @package Prefix Rest API
* @since 1.0.0
*/
if ( ! class_exists( 'Prefix_Rest_API' ) ) :
/**
* Prefix_Rest_API
*
* @since 1.0.0
*/
class Prefix_Rest_API {
/**
* Instance
*
* @since 1.0.0
*
* @access private
* @var object Class object.
*/
private static $instance;
/**
* 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, 'api_actions' ) );
}
/**
* Register Route's
*
* @since 1.0.0
* @return void
*/
function api_actions() {
register_rest_route(
'prefix/v1', '/info',
array(
array(
'methods' => 'GET',
'callback' => array( $this, 'info_callback' ),
),
)
);
}
/**
* Retrieves all products.
*
* @since 1.0.0
* @access public
*
* @param WP_REST_Request $request Full details about the request.
* @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
*/
public function info_callback( $request ) {
return rest_ensure_response( 'Hello World' );
}
}
/**
* Initialize class object with 'get_instance()' method
*/
Prefix_Rest_API::get_instance();
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment