### Registering Product Routes and Endpoints Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints This example demonstrates how to register a route for '/products' with two endpoints: one for GET requests to retrieve products and another for POST requests to create a product. It includes the callback functions for each endpoint. ```APIDOC ## GET /wp-json/my-shop/v1/products ### Description Retrieves a list of products. ### Method GET ### Endpoint /wp-json/my-shop/v1/products ### Parameters #### Query Parameters None explicitly documented. ### Request Example None explicitly documented. ### Response #### Success Response (200) - products (array) - An array of product data. #### Response Example { "1": "I am product 1", "2": "I am product 2", "3": "I am product 3" } ## POST /wp-json/my-shop/v1/products ### Description Creates a new product. ### Method POST ### Endpoint /wp-json/my-shop/v1/products ### Parameters #### Request Body None explicitly documented. ### Request Example None explicitly documented. ### Response #### Success Response (200) - message (string) - Confirmation message that the product has been created. #### Response Example { "Product has been created": "" } ``` -------------------------------- ### Model Examples Source: https://developer.wordpress.org/rest-api/using-the-rest-api/backbone-javascript-client Examples demonstrating how to use Backbone.js models to interact with WordPress API resources like posts and categories. ```APIDOC ## Model Operations ### Create a new post ```javascript var post = new wp.api.models.Post( { title: 'This is a test post' } ); post.save(); ``` ### Load an existing post ```javascript var post = new wp.api.models.Post( { id: 1 } ); post.fetch(); ``` ### Get a post's categories ```javascript post.getCategories().done( function( postCategories ) { // ... do something with the categories. console.log( postCategories[0].name ); // response -> "Uncategorized" } ); ``` ### Get a post's author ```javascript post.getAuthorUser().done( function( user ){ console.log( user.get( "name" ) ); } ); ``` ### Get a post's featured image ```javascript post.getFeaturedMedia().done( function( image ){ console.log( image ); } ``` ### Set post categories ```javascript post.setCategories( [ "apples", "oranges" ] ); ``` ### Get all categories ```javascript var allCategories = new wp.api.collections.Categories(); allCategories.fetch(); var appleCategory = allCategories.findWhere( { slug: "apples" } ); ``` ### Add a category to a post ```javascript appleCategory.set( "parent_post", post.get( "id" ) ); postCategories.create( appleCategory.toJSON(), { type: "POST" } ); ``` ### Remove a category from a post ```javascript postCategories.at( 0 ).destroy(); ``` ### Re-fetch categories to check results ```javascript postCategories = post.getCategories(); postCategories.at( 0 ).get( "name" ); // response -> "apples" ``` ``` -------------------------------- ### Update a Plugin Example Request Source: https://developer.wordpress.org/rest-api/reference/plugins This section is intended for updating a plugin, but the example request is missing. -------------------------------- ### Retrieve All Themes - Example Request Source: https://developer.wordpress.org/rest-api/reference/themes Use this endpoint to retrieve a list of all available themes. No specific arguments are required for a general listing. ```bash $ curl https://example.com/wp-json/wp/v2/themes ``` -------------------------------- ### List Users - Example Request Source: https://developer.wordpress.org/rest-api/reference/users Use this command to retrieve a collection of users. The response can be filtered using URL query parameters. ```bash $ curl https://example.com/wp-json/wp/v2/users ``` -------------------------------- ### Example Request to Retrieve a Template Part Revision Source: https://developer.wordpress.org/rest-api/reference/wp_template_part-revisions Example cURL command to fetch a specific template part revision. Replace placeholders with actual IDs and domain. ```bash $ curl https://example.com/wp-json/wp/v2/template-parts//autosaves/ ``` -------------------------------- ### Valid Object Example Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/schema An example of an object that conforms to the schema requiring 'name' and 'color' properties. ```json { "name": "Primary", "color": "#ff6d69" } ``` -------------------------------- ### Custom REST Route Example Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints This example demonstrates how to register and handle custom REST API routes for reading, creating, updating, and deleting items. ```APIDOC ## GET /vendor/v1/route ### Description Retrieves a collection of items. ### Method GET ### Endpoint /vendor/v1/route ### Parameters #### Query Parameters - **context** (string) - Optional - The context for the response. ### Response #### Success Response (200) - **data** (array) - An array of items. #### Response Example ```json { "data": [] } ``` ## POST /vendor/v1/route ### Description Creates a new item in the collection. ### Method POST ### Endpoint /vendor/v1/route ### Parameters #### Request Body - **item** (object) - Required - The data for the new item. ### Response #### Success Response (200) - **data** (object) - The created item. #### Response Example ```json { "data": {} } ``` ## GET /vendor/v1/route/{id} ### Description Retrieves a single item from the collection. ### Method GET ### Endpoint /vendor/v1/route/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the item to retrieve. #### Query Parameters - **context** (string) - Optional - The context for the response. ### Response #### Success Response (200) - **data** (object) - The requested item. #### Response Example ```json { "data": {} } ``` ## EDIT /vendor/v1/route/{id} ### Description Updates an existing item in the collection. ### Method EDIT ### Endpoint /vendor/v1/route/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the item to update. #### Request Body - **item** (object) - Required - The updated data for the item. ### Response #### Success Response (200) - **data** (object) - The updated item. #### Response Example ```json { "data": {} } ``` ## DELETE /vendor/v1/route/{id} ### Description Deletes an item from the collection. ### Method DELETE ### Endpoint /vendor/v1/route/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the item to delete. #### Query Parameters - **force** (boolean) - Optional - Whether to force the deletion. ### Response #### Success Response (200) - **data** (object) - A success message. #### Response Example ```json { "data": { "deleted": true, "previous": {} } } ``` ## GET /vendor/v1/route/schema ### Description Retrieves the schema for the custom route. ### Method GET ### Endpoint /vendor/v1/route/schema ### Response #### Success Response (200) - **schema** (object) - The schema for the route. #### Response Example ```json { "schema": {} } ``` ``` -------------------------------- ### Retrieve a Plugin Example Request Source: https://developer.wordpress.org/rest-api/reference/plugins Use this endpoint to retrieve a specific plugin record. The `context` argument determines the fields present in the response. ```bash $ curl https://example.com/wp-json/wp/v2/plugins ``` -------------------------------- ### Example Post Response with Links Source: https://developer.wordpress.org/rest-api/linking-and-embedding Demonstrates the `_links` property in a single post response, showing how to access collection and author information. ```json { "id": 42, "_links": { "collection": [ { "href": "https://example.com/wp-json/wp/v2/posts" } ], "author": [ { "href": "https://example.com/wp-json/wp/v2/users/1", "embeddable": true } ] } } ``` -------------------------------- ### Example Request for Retrieving a Post Revision Source: https://developer.wordpress.org/rest-api/reference/post-revisions Example cURL command to retrieve a specific post revision. Replace placeholders with actual IDs and domain. ```bash $ curl https://example.com/wp-json/wp/v2/posts//autosaves/ ``` -------------------------------- ### Get Individual Book by ID Source: https://developer.wordpress.org/rest-api/requests This example demonstrates how to register a REST API route that accepts a URL parameter for an 'id' to retrieve a specific book. It shows how to access the 'id' from the request object within the callback function. ```APIDOC ## GET /my-namespace/v1/books/(?P\d+) ### Description Retrieves a specific book by its ID. ### Method GET ### Endpoint `/my-namespace/v1/books/(?P\d+)` ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the book. ### Request Example `GET https://ourawesomesite.com/wp-json/my-namespace/v1/books/5` ### Response #### Success Response (200) - **string** - The title of the book if found. #### Response Example { "example": "Clean Code" } #### Error Response (404) - **WP_Error** - If the book with the specified ID does not exist. ### Code Example (PHP) ```php // Register our individual books endpoint. function prefix_register_book_route() { register_rest_route( 'my-namespace/v1', '/books/(?P\d+)', array( // Supported methods for this endpoint. WP_REST_Server::READABLE translates to GET. 'methods' => WP_REST_Server::READABLE, // Register the callback for the endpoint. 'callback' => 'prefix_get_book', ) ); } add_action( 'rest_api_init', 'prefix_register_book_route' ); /** * Our registered endpoint callback. Notice how we are passing in $request as an argument. * By default, the WP_REST_Server will pass in the matched request object to our callback. * * @param WP_REST_Request $request The current matched request object. */ function prefix_get_book( $request ) { // Here we are accessing the path variable 'id' from the $request. $book = prefix_get_the_book( $request['id'] ); return rest_ensure_response( $book ); } // A simple function that grabs a book title from our books by ID. function prefix_get_the_book( $id ) { $books = array( 'Design Patterns', 'Clean Code', 'Refactoring', 'Structure and Interpretation of Computer Programs', ); $book = ''; if ( isset( $books[ $id ] ) ) { // Grab the matching book. $book = $books[ $id ]; } else { // Error handling. return new WP_Error( 'rest_not_found', esc_html__( 'The book does not exist', 'my-text-domain' ), array( 'status' => 404 ) ); } return $book; } ``` ``` -------------------------------- ### Retrieve All Widgets - Example Request Source: https://developer.wordpress.org/rest-api/reference/widgets Use this endpoint to retrieve a list of all widget records. The `context` argument can filter the fields present in the response. ```bash $ curl https://example.com/wp-json/wp/v2/widgets ``` -------------------------------- ### Model Examples: Creating and Editing Posts Source: https://developer.wordpress.org/rest-api/backbone-javascript-client Demonstrates how to create a new post, load an existing post, and manage its categories, author, and featured image using the Backbone.js models. ```APIDOC ## Model Operations ### Create a new post ```javascript var post = new wp.api.models.Post( { title: 'This is a test post' } ); post.save(); ``` ### Load an existing post ```javascript var post = new wp.api.models.Post( { id: 1 } ); post.fetch(); ``` ### Get a post's categories ```javascript post.getCategories().done( function( postCategories ) { console.log( postCategories[0].name ); // e.g., "Uncategorized" } ); ``` ### Get a post's author ```javascript post.getAuthorUser().done( function( user ){ console.log( user.get( "name" ) ); } ``` ### Get a post's featured image ```javascript post.getFeaturedMedia().done( function( image ){ console.log( image ); } ``` ### Set post categories ```javascript post.setCategories( [ "apples", "oranges" ] ); ``` ### Get all categories ```javascript var allCategories = new wp.api.collections.Categories(); allCategories.fetch(); var appleCategory = allCategories.findWhere( { slug: "apples" } ); ``` ### Add a category to a post ```javascript appleCategory.set( "parent_post", post.get( "id" ) ); postCategories.create( appleCategory.toJSON(), { type: "POST" } ); ``` ### Remove a category from a post ```javascript postCategories.at( 0 ).destroy(); ``` ### Re-fetch categories to check results ```javascript postCategories = post.getCategories(); console.log( postCategories.at( 0 ).get( "name" ) ); // e.g., "apples" ``` ``` -------------------------------- ### Registering a Custom Endpoint Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints This example demonstrates how to register a custom GET endpoint for retrieving a post title by author ID. It includes the callback function and the registration using `register_rest_route` hooked into `rest_api_init`. ```APIDOC ## Registering a Custom Endpoint ### Description This example registers a custom GET endpoint that retrieves the latest post title for a given author ID. ### Method GET ### Endpoint `/myplugin/v1/author/(?P\d+)` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the author. ### Request Example ``` GET /wp-json/myplugin/v1/author/1 ``` ### Response #### Success Response (200) - **title** (string) - The post title for the latest post by the author. #### Response Example ```json { "title": "Example Post Title" } ``` ### Code Implementation ```php $data['id'], ) ); if ( empty( $posts ) ) { return null; } return $posts[0]->post_title; } add_action( 'rest_api_init', function () { register_rest_route( 'myplugin/v1', '/author/(?P\d+)', array( 'methods' => 'GET', 'callback' => 'my_awesome_func', ) ); } ); ?> ``` ``` -------------------------------- ### API Index with Namespaces Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints An example of the API index response, showing available namespaces. Custom namespaces should follow the 'vendor/v1' pattern to prevent conflicts. ```json { "name": "WordPress Site", "description": "Just another WordPress site", "url": "http://example.com/", "namespaces": [ "wp/v2", "vendor/v1", "myplugin/v1", "myplugin/v2", ] } ``` -------------------------------- ### Registering a Custom Endpoint with Arguments Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints This example demonstrates how to register a new REST API endpoint '/colors' within the 'my-colors/v1' namespace. It includes a callback function `prefix_get_colors` to handle requests and defines a 'filter' argument using `prefix_get_color_arguments` which allows filtering the collection of colors by 'red', 'green', or 'blue'. The endpoint is accessible via GET requests. ```APIDOC ## GET /my-colors/v1/colors ### Description Retrieves a collection of colors, with an optional filter parameter to narrow down the results. ### Method GET ### Endpoint /my-colors/v1/colors ### Parameters #### Query Parameters - **filter** (string) - Optional - The filter parameter is used to filter the collection of colors. Allowed values: 'red', 'green', 'blue'. ### Request Example ```json { "example": "GET https://ourawesomesitem.com/my-colors/v1/colors?filter=blue" } ``` ### Response #### Success Response (200) - **colors** (array) - A list of colors. If a filter is applied, only matching colors are returned. #### Response Example ```json { "example": [ "blue", "blue" ] } ``` ``` -------------------------------- ### Discover API Extensions (Namespaces) Source: https://developer.wordpress.org/rest-api/using-the-rest-api/discovery The API index exposes 'namespaces' to identify supported extensions. This example shows basic API infrastructure with oEmbed support. ```json { "name": "Example WordPress Site", "namespaces": [ "oembed/1.0/" ] } ``` -------------------------------- ### Collection Examples: Fetching and Filtering Posts Source: https://developer.wordpress.org/rest-api/backbone-javascript-client Illustrates how to fetch collections of posts, including specifying the number of items per page, filtering by order, and paginating results. ```APIDOC ## Collection Operations ### Get the last 10 posts ```javascript var postsCollection = new wp.api.collections.Posts(); postsCollection.fetch(); ``` ### Get the last 25 posts ```javascript postsCollection.fetch( { data: { per_page: 25 } } ); ``` ### Filter posts by order and orderby ```javascript postsCollection.fetch( { data: { 'filter': { 'orderby': 'title', 'order': 'ASC' } } } ); ``` ### Get the next page of results ```javascript postsCollection.more(); ``` ### Get a specific page of results (e.g., page 5) ```javascript posts.fetch( { data: { page: 5 } } ); ``` ### Check if there are more posts available ```javascript posts.hasMore(); ``` ``` -------------------------------- ### Creating a Custom 'Hello World' Endpoint Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints This example demonstrates how to register a custom route and endpoint that returns a simple greeting. It uses `register_rest_route` to define the namespace, resource path, HTTP method, and callback function. ```APIDOC ## GET /hello-world/v1/phrase ### Description Returns a simple "Hello World" greeting. ### Method GET ### Endpoint /hello-world/v1/phrase ### Parameters None ### Request Example None ### Response #### Success Response (200) - **string** - The greeting message. #### Response Example "Hello World, this is the WordPress REST API" ``` -------------------------------- ### Retrieve Specific Theme - Example Request Source: https://developer.wordpress.org/rest-api/reference/themes Query this endpoint to retrieve a specific theme record by its stylesheet. The stylesheet parameter uniquely identifies the theme. ```bash $ curl https://example.com/wp-json/wp/v2/themes/?) ``` -------------------------------- ### Themes Source: https://developer.wordpress.org/rest-api/reference Endpoints for retrieving information about installed themes. ```APIDOC ## GET /wp/v2/themes ### Description Retrieves a list of installed themes. ### Method GET ### Endpoint /wp/v2/themes ``` -------------------------------- ### List Categories - Example Request Source: https://developer.wordpress.org/rest-api/reference/categories Use this cURL command to retrieve a collection of categories. You can filter the results using URL query parameters. ```bash $ curl https://example.com/wp-json/wp/v2/categories ``` -------------------------------- ### Delete a Plugin Example Request Source: https://developer.wordpress.org/rest-api/reference/plugins Use this endpoint to delete a specific plugin. The `context` argument determines the fields present in the response. ```bash $ curl -X DELETE https://example.com/wp-json/wp/v2/plugins/?) ``` -------------------------------- ### Retrieve a Specific Plugin Example Request Source: https://developer.wordpress.org/rest-api/reference/plugins Query this endpoint to retrieve a specific plugin record using its ID or slug. The `context` argument determines the fields present in the response. ```bash $ curl https://example.com/wp-json/wp/v2/plugins/?) ``` -------------------------------- ### Retrieve a Specific Widget - Example Request Source: https://developer.wordpress.org/rest-api/reference/widgets Query this endpoint to retrieve a specific widget record by its ID. The `context` argument can filter the fields present in the response. ```bash $ curl https://example.com/wp-json/wp/v2/widgets/ ``` -------------------------------- ### Registering Meta Fields for REST API Access with `register_meta` Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses This example shows how to make existing or new meta fields accessible via the REST API by using the `register_meta` function and setting the `show_in_rest` argument to `true`. ```APIDOC ## Registering Meta Fields for REST API ### Description Allows meta fields associated with specific object types to be accessible and manageable via the REST API. ### Function Signature `register_meta( $object_type, $meta_key, $args ) ` ### Parameters * `$object_type` (string): The object type for which the meta field is being registered (e.g., 'post', 'comment', 'user'). * `$meta_key` (string): The name of the meta key. * `$args` (array): An array of arguments for the meta field: * `type` (string): The data type of the meta value (e.g., 'string', 'integer', 'boolean', 'number'). * `description` (string): A description of the meta field, shown in the REST API schema. * `single` (bool): Whether to return a single value (true) or an array of values (false). Defaults to false. * `show_in_rest` (bool): Set to `true` to make the meta field accessible in the REST API. Defaults to `false`. ### Example: Registering a post meta field ```php 'string', // Shown in the schema for the meta key. 'description' => 'A meta key associated with a string meta value.', // Return a single value of the type. 'single' => true, // Show in the WP REST API response. Default: false. 'show_in_rest' => true, ); register_meta( $object_type, 'my_meta_key', $meta_args ); ?> ``` ### Usage Once registered with `show_in_rest` set to `true`, the meta field can be updated via POST requests to the relevant object endpoint (e.g., `wp-json/wp/v2/posts/`). ``` -------------------------------- ### Registering a REST API Endpoint with Permissions Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints This example shows how to register a new REST API endpoint with both a data retrieval callback and a permissions check callback. Ensure the user has 'edit_posts' capability to access the private data. ```php /** * This is our callback function that embeds our resource in a WP_REST_Response */ function prefix_get_private_data() { // rest_ensure_response() wraps the data we want to return into a WP_REST_Response, and ensures it will be properly returned. return rest_ensure_response( 'This is private data.' ); } /** * This is our callback function that embeds our resource in a WP_REST_Response */ function prefix_get_private_data_permissions_check() { // Restrict endpoint to only users who have the edit_posts capability. if ( ! current_user_can( 'edit_posts' ) ) { return new WP_Error( 'rest_forbidden', esc_html__( 'OMG you can not view private data.', 'my-text-domain' ), array( 'status' => 401 ) ); } // This is a black-listing approach. You could alternatively do this via white-listing, by returning false here and changing the permissions check. return true; } /** * This function is where we register our routes for our example endpoint. */ function prefix_register_example_routes() { // register_rest_route() handles more arguments but we are going to stick to the basics for now. register_rest_route( 'my-plugin/v1', '/private-data', array( // By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended. 'methods' => WP_REST_Server::READABLE, // Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class. 'callback' => 'prefix_get_private_data', // Here we register our permissions callback. The callback is fired before the main callback to check if the current user can access the endpoint. 'permission_callback' => 'prefix_get_private_data_permissions_check', ) ); } add_action( 'rest_api_init', 'prefix_register_example_routes' ); ``` -------------------------------- ### WordPress REST API JSONP Callback Example Source: https://developer.wordpress.org/rest-api/global-parameters Shows how to enable JSONP responses for cross-domain requests using the `_jsonp` parameter. The API prepends the specified callback function to the JSON data, allowing it to be loaded via a script tag. ```html ``` -------------------------------- ### Registering a Custom Endpoint with Permissions Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints This example demonstrates how to register a new REST API endpoint for retrieving private data. It includes a main callback function to fetch the data and a permissions callback to control access based on user capabilities. ```APIDOC ## GET /my-plugin/v1/private-data ### Description Retrieves private data after checking user permissions. ### Method GET ### Endpoint /my-plugin/v1/private-data ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **data** (string) - The private data string. #### Response Example { "data": "This is private data." } #### Error Response (401) - **code** (string) - 'rest_forbidden' - **message** (string) - 'OMG you can not view private data.' - **data.status** (integer) - 401 ``` -------------------------------- ### Retrieve a Tag Example Request Source: https://developer.wordpress.org/rest-api/reference/tags Use this cURL command to retrieve a specific tag record by its ID. Replace `` with the actual ID of the tag you want to fetch. ```bash $ curl https://example.com/wp-json/wp/v2/tags/ ``` -------------------------------- ### Registering a Comment Resource with Schema Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/schema This example demonstrates how to register a REST API route for comments and associate it with a schema definition. The schema is defined in `prefix_get_comment_schema` and is accessible via an OPTIONS request. ```APIDOC ## GET /wp-json/my-namespace/v1/comments ### Description Retrieves a list of the five most recent comments. ### Method GET ### Endpoint /wp-json/my-namespace/v1/comments ### Parameters #### Query Parameters - **number** (integer) - Optional - The number of comments to retrieve. Defaults to 5. ### Response #### Success Response (200) - **id** (integer) - Unique identifier for the comment. - **author** (integer) - The ID of the user who authored the comment. - **content** (string) - The content of the comment. ### Request Example ```json { "example": "GET /wp-json/my-namespace/v1/comments" } ``` ### Response Example ```json { "example": [ { "id": 1, "author": 1, "content": "This is a sample comment." } ] } ``` ## OPTIONS /wp-json/my-namespace/v1/comments ### Description Returns the schema definition for the comment resource. ### Method OPTIONS ### Endpoint /wp-json/my-namespace/v1/comments ### Response #### Success Response (200) - **$schema** (string) - The JSON schema draft version. - **title** (string) - The title of the resource (e.g., 'comment'). - **type** (string) - The type of the resource (e.g., 'object'). - **properties** (object) - An object containing the definitions for each property of the resource. - **id** (object) - Schema for the comment ID. - **description** (string) - Description of the ID field. - **type** (string) - Data type of the ID field (e.g., 'integer'). - **context** (array) - Contexts in which the field is available. - **readonly** (boolean) - Indicates if the field is read-only. - **author** (object) - Schema for the comment author. - **description** (string) - Description of the author field. - **type** (string) - Data type of the author field (e.g., 'integer'). - **content** (object) - Schema for the comment content. - **description** (string) - Description of the content field. - **type** (string) - Data type of the content field (e.g., 'string'). ### Response Example ```json { "example": { "$schema": "http://json-schema.org/draft-04/schema#", "title": "comment", "type": "object", "properties": { "id": { "description": "Unique identifier for the object.", "type": "integer", "context": ["view", "edit", "embed"], "readonly": true }, "author": { "description": "The id of the user object, if author was a user.", "type": "integer" }, "content": { "description": "The content for the object.", "type": "string" } } } } ``` ``` -------------------------------- ### Registering a Custom Field with `register_rest_field` Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses This example demonstrates how to add a new field, 'karma', to comment responses using the `register_rest_field` function. It includes callbacks for getting and updating the field, as well as defining its schema. ```APIDOC ## Registering a Custom Field ### Description Adds a custom field to a specific object type in the REST API response. ### Function Signature `register_rest_field( $object_type, $attribute, $args ) ` ### Parameters * `$object_type` (string|array): The object type(s) to register the field for (e.g., 'post', 'comment', 'user'). * `$attribute` (string): The name of the field to be added to the response. * `$args` (array): An array containing callback functions: * `get_callback` (callable): Function to retrieve the field's value. * `update_callback` (callable): Function to update the field's value (optional, makes field read-only if omitted). * `schema` (array): Schema definition for the field (optional). ### Action Hook Fields should be registered using the `rest_api_init` action hook. ### Example: Adding 'karma' field to comment responses ```php function( $comment_arr ) { $comment_obj = get_comment( $comment_arr['id'] ); return (int) $comment_obj->comment_karma; }, 'update_callback' => function( $karma, $comment_obj ) { $ret = wp_update_comment( array( 'comment_ID' => $comment_obj->comment_ID, 'comment_karma' => $karma ) ); if ( false === $ret ) { return new WP_Error( 'rest_comment_karma_failed', __( 'Failed to update comment karma.' ), array( 'status' => 500 ) ); } return true; }, 'schema' => array( 'description' => __( 'Comment karma.' ), 'type' => 'integer' ), ) ); } ); ?> ``` ``` -------------------------------- ### Register a Custom REST API Route Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints Registers a new REST API route with a GET method and a custom callback function. This should be hooked into 'rest_api_init'. The namespace 'myplugin/v1' and route '/author/(?P\d+)' are examples. ```php \d+)', array( 'methods' => 'GET', 'callback' => 'my_awesome_func', ) ); } ); ``` -------------------------------- ### Register Custom REST API Route with Schema Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/schema Register a custom REST API route for comments and associate a schema callback. This setup allows for GET requests to retrieve comments and OPTIONS requests to retrieve the schema definition. ```php function prefix_register_my_comment_route() { register_rest_route( 'my-namespace/v1', '/comments', array( // Notice how we are registering multiple endpoints the 'schema' equates to an OPTIONS request. array( 'methods' => 'GET', 'callback' => 'prefix_get_comment_sample', ), // Register our schema callback. 'schema' => 'prefix_get_comment_schema', ) ); } add_action( 'rest_api_init', 'prefix_register_my_comment_route' ); ``` -------------------------------- ### Create a Nav Menu Source: https://developer.wordpress.org/rest-api/reference/nav_menus Use this endpoint to create a new navigation menu. Required arguments include the menu name. ```bash POST /wp/v2/menus ``` -------------------------------- ### Registering a Sanitized Data Endpoint Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints This example demonstrates how to register a REST API route with argument sanitization. It includes callbacks for getting the item, validating the 'data' argument, sanitizing it using `sanitize_text_field`, and defining the arguments for the route. The `rest_api_init` action hook is used to register the route. ```php /** * This is our callback function that embeds our resource in a WP_REST_Response. * * The parameter is already sanitized by this point so we can use it without any worries. */ function prefix_get_item( $request ) { if ( isset( $request['data'] ) ) { return rest_ensure_response( $request['data'] ); } return new WP_Error( 'rest_invalid', esc_html__( 'The data parameter is required.', 'my-text-domain' ), array( 'status' => 400 ) ); } /** * Validate a request argument based on details registered to the route. * * @param mixed $value Value of the 'filter' argument. * @param WP_REST_Request $request The current request object. * @param string $param Key of the parameter. In this case it is 'filter'. * @return WP_Error|boolean */ function prefix_data_arg_validate_callback( $value, $request, $param ) { // If the 'data' argument is not a string return an error. if ( ! is_string( $value ) ) { return new WP_Error( 'rest_invalid_param', esc_html__( 'The filter argument must be a string.', 'my-text-domain' ), array( 'status' => 400 ) ); } } /** * Sanitize a request argument based on details registered to the route. * * @param mixed $value Value of the 'filter' argument. * @param WP_REST_Request $request The current request object. * @param string $param Key of the parameter. In this case it is 'filter'. * @return WP_Error|boolean */ function prefix_data_arg_sanitize_callback( $value, $request, $param ) { // It is as simple as returning the sanitized value. return sanitize_text_field( $value ); } /** * We can use this function to contain our arguments for the example product endpoint. */ function prefix_get_data_arguments() { $args = array(); // Here we are registering the schema for the filter argument. $args['data'] = array( // description should be a human readable description of the argument. 'description' => esc_html__( 'The data parameter is used to be sanitized and returned in the response.', 'my-text-domain' ), // type specifies the type of data that the argument should be. 'type' => 'string', // Set the argument to be required for the endpoint. 'required' => true, // We are registering a basic validation callback for the data argument. 'validate_callback' => 'prefix_data_arg_validate_callback', // Here we register the validation callback for the filter argument. 'sanitize_callback' => 'prefix_data_arg_sanitize_callback', ); return $args; } /** * This function is where we register our routes for our example endpoint. */ function prefix_register_example_routes() { // register_rest_route() handles more arguments but we are going to stick to the basics for now. register_rest_route( 'my-plugin/v1', '/sanitized-data', array( // By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended. 'methods' => WP_REST_Server::READABLE, // Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class. 'callback' => 'prefix_get_item', // Here we register our permissions callback. The callback is fired before the main callback to check if the current user can access the endpoint. 'args' => prefix_get_data_arguments(), ) ); } add_action( 'rest_api_init', 'prefix_register_example_routes' ); ``` -------------------------------- ### Create and Save a New Post Source: https://developer.wordpress.org/rest-api/backbone-javascript-client Demonstrates how to instantiate a new Post model and save it to the server. ```javascript // Create a new post var post = new wp.api.models.Post( { title: 'This is a test post' } ); post.save(); ``` -------------------------------- ### Invalid Object Example (Invalid Color Format) Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/schema An example of an object that fails validation because the 'color' property is not a valid hex color. ```json { "name": "Primary", "color": "orange" } ``` -------------------------------- ### Get Post Author Source: https://developer.wordpress.org/rest-api/backbone-javascript-client Fetches the User model for the author of a post. ```javascript // Get a posts author User model. post.getAuthorUser().done( function( user ){ // ... do something with user console.log( user.get( "name" ) ); } ); ``` -------------------------------- ### Get Post Featured Image Source: https://developer.wordpress.org/rest-api/backbone-javascript-client Retrieves the Media model for the featured image of a post. ```javascript // Get a posts featured image Media model. post.getFeaturedMedia().done( function( image ){ // ... do something with image console.log( image ); } ); ``` -------------------------------- ### Create a Widget Source: https://developer.wordpress.org/rest-api/reference/widgets Create a new widget. ```APIDOC ## Create a Widget ### Description Create a new widget. ### Method POST ### Endpoint /wp/v2/widgets ### Parameters #### Request Body - **id_base** (string) - Required - The type of the widget. Corresponds to ID in widget-types endpoint. - **sidebar** (string) - Optional - The sidebar the widget belongs to. Default: `wp_inactive_widgets` - **instance** (object) - Optional - Instance settings of the widget, if supported. - **form_data** (string) - Optional - URL-encoded form data from the widget admin form. Used to update a widget that does not support instance. Write only. ``` -------------------------------- ### Get Post Revisions by Parent ID Source: https://developer.wordpress.org/rest-api/backbone-javascript-client Initializes a collection to retrieve all revisions for a specific post ID. ```javascript var revisions = new wp.api.collections.PostRevisions({}, { parent: 1 }); ``` -------------------------------- ### Get Post Categories Source: https://developer.wordpress.org/rest-api/backbone-javascript-client Retrieves the categories associated with a post. Uses embedded data if available for immediate resolution. ```javascript // Get a collection of the post's categories (returns a promise) // Uses _embedded data if available, in which case promise resolves immediately. post.getCategories().done( function( postCategories ) { // ... do something with the categories. // The new post has an single Category: Uncategorized console.log( postCategories[0].name ); // response -> "Uncategorized" } ); ``` -------------------------------- ### Create a Template Source: https://developer.wordpress.org/rest-api/reference/wp_templates Create a new template record. Requires parameters like slug, theme, type, content, title, description, status, and author. ```APIDOC ## POST /wp/v2/templates ### Description Creates a new template record. ### Method POST ### Endpoint /wp/v2/templates ### Parameters #### Request Body - **slug** (string) - Required - Unique slug identifying the template. - **theme** (string) - Optional - Theme identifier for the template. - **type** (string) - Optional - Type of template. - **content** (object or string) - Optional - Content of template. - **title** (object or string) - Optional - Title of template. - **description** (string) - Optional - Description of template. - **status** (string) - Optional - Status of template. Default: `publish`. One of: `publish`, `future`, `draft`, `pending`, `private`. - **author** (integer) - Optional - The ID for the author of the template. ``` -------------------------------- ### Get Post Author User Model Source: https://developer.wordpress.org/rest-api/using-the-rest-api/backbone-javascript-client Retrieve the User model for the author of a post. The promise resolves with the user data. ```javascript post.getAuthorUser().done( function( user ){ // ... do something with user console.log( user.get( "name" ) ); } ); ``` -------------------------------- ### Create a Nav Menu Item Source: https://developer.wordpress.org/rest-api/reference/nav_menu_items Create a new nav_menu_item. ```APIDOC ## POST /wp/v2/menu-items ### Description Create a new nav_menu_item. ### Method POST ### Endpoint /wp/v2/menu-items ### Parameters #### Request Body - **title** (string) - Required - The title for the object. - **menu_order** (integer) - Required - The DB ID of the nav_menu_item that is this item's menu parent, if any, otherwise 0. - **parent** (integer) - Optional - The ID for the parent of the object. - **object_id** (integer) - Optional - The database ID of the original object this menu item represents, for example the ID for posts or the term_id for categories. - **object** (string) - Optional - The type of object originally represented, such as "category", "post", or "attachment". - **type** (string) - Optional - The family of objects originally represented, such as "post_type" or "taxonomy". One of: `taxonomy`, `post_type`, `post_type_archive`, `custom`. - **url** (string) - Optional - The URL to which this menu item points. - **target** (string) - Optional - The target attribute of the link element for this menu item. One of: `_blank`, ``. - **attr_title** (string) - Optional - Text for the title attribute of the link element for this menu item. - **description** (string) - Optional - The description of this menu item. - **classes** (array) - Optional - Class names for the link element of this menu item. - **xfn** (array) - Optional - The XFN relationship expressed in the link of this menu item. - **status** (string) - Optional - A named status for the object. One of: `publish`, `future`, `draft`, `pending`, `private`. - **meta** (object) - Optional - Meta fields. ```