diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..496ee2c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.DS_Store \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..b38ffe8 --- /dev/null +++ b/README.md @@ -0,0 +1,28 @@ +# WordPress Router API + +Simple WordPress plugin to provide a router-like interface with applications consuming the WordPress REST API. + +## Installing + +Simply copy the project directory into `wp-content/plugins` and activate it via the plugins admin page, or drop `wordpress-router-api.php` into the `wp-content/mu-plugins` directory. + +## Usage + +The plugin exposes a single route to the API at the following URL via a GET request: + +`http://MYWORDPRESSURL/wp-json/wp-router-api/v1/by/path` + +It accept a single paramater named `path`. + +Pass the whole path of a post you'd like to retrieve: + +`http://MYWORDPRESSURL/wp-json/wp-router-api/v1/by/path?=/path/to/post` + +The response will be a standard WordPress post object, with the following additional properties: + +* `children`: An array of the returned posts children (in case you're unaware, that includes attachments). +* `fields`: An array of custom fields associated with the post (any data stored as an array will be unserialized). + +## Technical Notes + +Tested with WordPress v4.9.8, PHP 7.1.6 \ No newline at end of file diff --git a/index.php b/index.php new file mode 100644 index 0000000..a378c30 --- /dev/null +++ b/index.php @@ -0,0 +1,2 @@ + WP_REST_Server::READABLE, + 'callback' => array($this, 'get_object_by_path'), + ) + ); + } + + public function get_object_by_path($request) { + $parameters = $request->get_query_params(); + $path = $parameters['path']; + + return array ( + 'parameters' => $parameters, + 'path' => $path, + 'post' => $this->get_obj_by_path($path), + ); + } + + /** + * Accepts a string with the provided path and returns a post object, + * or null if not found. + */ + private function get_obj_by_path($path) { + $object = null; + $page = get_page_by_path($path); + // If a page is not found, iterate through the current sites registered post types + // to attempt a match for the provided path. + if (!$page) { + foreach(get_post_types() as $post_type) { + $page = get_page_by_path(basename( untrailingslashit($path) ), OBJECT, $post_type); + if ($page) { + $object = $page; + } + } + } else { + $object = $page; + } + // Get this posts children. + $object->children = get_children($object->ID); + // For good measure lets get all the custom fields too. + $object->fields = get_post_custom($object->ID); + return $object; + } +} + +if ( ! function_exists ( 'wp_router_api_init' ) ) { + + function wp_router_api_init() { + $initializer = new WordPressRouterAPI(); + } + + add_action( 'init', 'wp_router_api_init' ); +}