Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2016
645
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.22 KB | None | 0 0
  1. <?php
  2.  
  3. // -----------------------------------------
  4. // stack overflow
  5. // -----------------------------------------
  6.  
  7. class my_api {
  8.  
  9.     public function __construct() {
  10.  
  11.         // -----------------------------------------
  12.         // rest routes
  13.         // -----------------------------------------
  14.  
  15.         // version
  16.         add_action('rest_api_init', function () {
  17.  
  18.             $version = '1';
  19.             $namespace = 'myapi/v' . $version;
  20.  
  21.             // get posts
  22.             register_rest_route($namespace, '/posts', array(
  23.                 'methods'   => WP_REST_Server::READABLE,
  24.                 'permission_callback' => array($this, 'auth_user'),
  25.                 'callback'  => array($this, 'posts'),
  26.             ));
  27.         });
  28.     }
  29.  
  30.     // -----------------------------------------
  31.     // endpoints
  32.     // -----------------------------------------
  33.  
  34.     public function posts($request) {
  35.  
  36.         $output = 'Latest Posts';
  37.  
  38.         return new WP_REST_Response($output, 200);
  39.     }
  40.  
  41.     // -----------------------------------------
  42.     // check nonce to verify user
  43.     // -----------------------------------------
  44.  
  45.     public function auth_user() {
  46.  
  47.         // get nonce
  48.         $nonce = isset($_SERVER['HTTP_X_WP_NONCE']) ? $_SERVER['HTTP_X_WP_NONCE'] : '';
  49.  
  50.         // verfiy nonce
  51.         $nonce = wp_verify_nonce($nonce, 'wp_rest');
  52.  
  53.         // return
  54.         return $nonce;
  55.     }
  56. }
  57.  
  58. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement