PHP WordPress - JSON Endpoint from add_rewrite_rule

<?php /* URL http://example.com/api/user_data/1 JSON { "success": true, "data": { "id": 1, "display_name": "your_username", "user_registered": "2015-11-12 05:00:00", "first": "First", "last": "Last Name" } } */ /** * Creates endpoint to convert ID to user data * * http://example.com/api/user_data/{id} * * WARNING: * Don't expose user data to the world. This is for DEMO purposes only. */ if ( ! class_exists( 'JSONEndpoint_UserData' ) ): /** * The code that registers the endpoint and handles the result */ class JSONEndpoint_UserData { const ENDPOINT_NAME = 'api/user_data'; // endpoint to capture const ENDPOINT_QUERY_NAME = '__api_user_data'; // turns to param // WordPress hooks public function run() { add_filter( 'query_vars', array( $this, 'add_query_vars' ), 0 ); add_action( 'parse_request', array( $this, 'sniff_requests' ), 0 ); add_action( 'init', array( $this, 'add_endpoint' ), 0 ); } // Add public query vars public function add_query_vars( $vars ) { $vars[] = static::ENDPOINT_QUERY_NAME; $vars[] = 'id'; return $vars; } // Add API Endpoint public function add_endpoint() { add_rewrite_rule( '^' . static::ENDPOINT_NAME . '/([^/]+)/?$', 'index.php?' . static::ENDPOINT_QUERY_NAME . '=1&id=$matches[1]', 'top' ); // ---> flush_rewrite_rules( true ); //// <---------- REMOVE THIS WHEN DONE TESTING // ---> } // Sniff Requests public function sniff_requests( $wp_query ) { global $wp; if ( isset( $wp->query_vars[ static::ENDPOINT_QUERY_NAME ] ) ) { $this->handle_request(); // handle it } } // Handle Requests protected function handle_request() { global $wp; // we only deal with number$ $id = is_numeric( $wp->query_vars[ 'id' ] ) ? absint( $wp->query_vars[ 'id' ] ) : false; if ( ! is_numeric( $id ) || ! $user = get_user_by( 'id', $id ) ) { wp_send_json_error( array( 'message' => 'Invalid User ID' ) ); } // ALLOWING ACCESS FROM ANYWHERE --- WE MIGHT WANT TO RESTRICT THE PLACES THAT CAN USE THIS header( "Access-Control-Allow-Origin: *" ); // prep the response $data = array( 'id' => $user->ID, 'display_name' => $user->data->display_name, 'user_registered' => $user->data->user_registered, 'first' => $user->first_name, 'last' => $user->last_name, ); // write the response wp_send_json_success( $data ); die(); // just in case } } $ep = new JSONEndpoint_UserData(); $ep->run(); endif; // JSONEndpoint_UserData
Creates endpoint to convert ID to user data - http://example.com/api/user_data/{id}

WARNING:
Don't expose user data to the world. This is for demo purposes only.

2 Responses

Best crafted, readable and understandable Wordpress JSON Endpoint class i've seen!

Well done :)

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.