|
| 1 | +<?php |
| 2 | +<?php |
| 3 | +if ( ! defined( 'ABSPATH' ) ) exit; |
| 4 | + |
| 5 | +/** |
| 6 | + * Extending REST API framework of WordPress |
| 7 | + * |
| 8 | + * @author Nirjhar Lo |
| 9 | + * @package wp-plugin-framework |
| 10 | + */ |
| 11 | +if ( ! class_exists( 'PLUGIN_CUSTOM_ROUTE' ) ) { |
| 12 | + |
| 13 | + class PLUGIN_CUSTOM_ROUTE extends WP_REST_Controller { |
| 14 | + |
| 15 | + |
| 16 | + /** |
| 17 | + * REST API routes |
| 18 | + * |
| 19 | + * @return Object |
| 20 | + */ |
| 21 | + public function register_routes() { |
| 22 | + |
| 23 | + $version = '1'; |
| 24 | + $namespace = 'vendor/v' . $version; |
| 25 | + $base = 'route'; |
| 26 | + |
| 27 | + //Available options for methods are CREATABLE, READABLE, EDITABLE, DELETABLE |
| 28 | + register_rest_route( $namespace, '/' . $base, array( |
| 29 | + 'methods' => WP_REST_Server::READABLE, |
| 30 | + 'callback' => array( $this, 'callback' ), |
| 31 | + 'permission_callback' => array( $this, 'permission' ), |
| 32 | + 'args' => array('sample', 'list', 'of', 'args'), |
| 33 | + ), |
| 34 | + } |
| 35 | + |
| 36 | + |
| 37 | + /** |
| 38 | + * The request handler |
| 39 | + * |
| 40 | + * @return Object |
| 41 | + */ |
| 42 | + public function callback() { |
| 43 | + |
| 44 | + $params = $request->get_params(); |
| 45 | + $items = array(); |
| 46 | + $data = $this->prepare_item_for_response( $items, $request ); |
| 47 | + |
| 48 | + if ( $data ) { |
| 49 | + return new WP_REST_Response( $data, 200 ); |
| 50 | + } else { |
| 51 | + return new WP_Error( 'status_code', __( 'message', 'text-domain' ) ); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + |
| 56 | + /** |
| 57 | + * Prevent unauthorized access here |
| 58 | + * |
| 59 | + * @return Bool |
| 60 | + */ |
| 61 | + public function permission() { |
| 62 | + |
| 63 | + return current_user_can( 'manage_options' ); |
| 64 | + } |
| 65 | + |
| 66 | + |
| 67 | + /** |
| 68 | + * Processing of request takes place here |
| 69 | + * |
| 70 | + * @param Array |
| 71 | + * @param Object |
| 72 | + * |
| 73 | + * @return Array |
| 74 | + */ |
| 75 | + protected function prepare_item_for_response($items, $request) { |
| 76 | + |
| 77 | + //Process the data in any way you like |
| 78 | + $data = compact($items, $request); |
| 79 | + return $data; |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments