Custom Post Type
The Custom_API_Endpoint
class is designed to facilitate the creation of custom endpoints for our project. For example, if we need to retrieve information about a page and, at the same time, information about a testimonial that is loaded on that page, the best approach is to create a custom endpoint that returns only the information we need.
This class helps us facilitate the creation of each of the necessary endpoints. We just need to pass a namespace, the route, the method, and the callback function.
You can find the full class implementation here.
Parameters:
-
namespace: It helps organize your API endpoints and ensures they don’t conflict with other APIs. In this case, ‘wp/v2/tf_api/’ represents a custom API namespace under the WordPress REST API version 2 (wp/v2). The suffix tf_api/ is specific to your custom API.
-
route: This defines the URL path for the specific endpoint. In this example, the route is ‘/another-endpoint’, which will append to the namespace, forming a complete URL such as: /wp/v2/tf_api/another-endpoint. When this URL is accessed, WordPress will call the corresponding function based on the specified method. With the following code, you obtain the URL to access the another-endpoint:
-
PHP :
$myURL = get_site_url()."/wp/v2/tf_api/another-endpoint/"
-
JS :
myURL = base_wp_api.root_url + "/wp-json/wp/v2/tf_api/another-endpoint"
For exmample, the complete URL for accessing the another-endpoint would look like this: http://localhost/wp-starter-kit-2024/wp-json/wp/v2/tf_api/another-endpoint/`
-
method: This specifies the HTTP method (such as GET, POST, PUT, DELETE) that the endpoint will respond to. In this case, ‘GET’ means the endpoint will be used to retrieve data. Example: ‘GET’ is commonly used for fetching data, while ‘POST’ is used for submitting or updating data.
-
callback_function: This refers to the function that will be executed when the endpoint is accessed. In this case, the function name is ‘another_callback_function’. This function contains the logic for what happens when the request is made to the endpoint. Example: ‘another_callback_function’ will process the data request and return the appropriate response.
The Custom_API_Endpoint
class can be easily implemented into any WordPress project.
Example Usage
<?php// Create an instance of the TerraLighthouse class with specified parametersnew Custom_API_Endpoint((object) array( 'namespace' => 'wp/v2/tf_api/', 'route' => '/another-endpoint', 'method' => 'GET', 'callback_function' => 'another_callback_function',));
public function another_callback_function($data) { $response = array( 'message' => 'Hello from the dynamic endpoint!', 'status' => 200, ); return new WP_REST_Response($response, 200);}?>