WordPress is one of the most popular content management systems (CMS) in the world, but WordPress has evolved beyond just supporting traditional blog content - thanks in large part to the WordPress REST API, a magical API that acts as a bridge between WordPress and other external web applications. This amazing API acts as a bridge between WordPress and other external web applications, allowing WordPress to better "chat" with other applications and create awesome web experiences together.
How does this API work? It utilizes something called "endpoints". With these endpoints, we can easily fetch or modify content from WordPress, and it's all in JSON, which is a language that everyone understands. You don't need to log into the WordPress backend to do this. Using WordPress becomes much more flexible and powerful.
![图片[1]-为开发人员定制 WordPress:开发定制 REST API 端点-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/04/image-778.png)
Understanding the WordPress REST API
The WordPress REST API is a powerful interface that allows to programmatically interact with WordPress websites using standard HTTP methods. Its default functionality includes accessing and manipulating various types of WordPress data, such as posts, pages, comments, users, and taxonomies, in a structured JSON format. It is also possible to perform CRUD operations on content remotely.
However, the real value of the WordPress REST API is its extensibility through custom endpoints. Custom endpoints can be created to tailor the API to specific needs, such as integrating additional functionality, third-party services, or unique data structures. This flexibility allows for highly customized and feature-rich applications to be built on top of WordPress.
How to plan your custom API endpoints
Planning the structure and usage of custom endpoints is key to efficient API development. Custom endpoints tailored to specific needs require careful consideration to ensure optimal functionality. Strategic planning promotes scalability and adaptability, as well as future-proofing endpoints to accommodate changing business needs.
![图片[2]-为开发人员定制 WordPress:开发定制 REST API 端点-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/04/image-779.png)
Plan your custom API endpoint support before implementation:
- Clarity of endpoint functionality: Planning endpoints clarifies the specific function of the endpoint, its expected data type and usage.
- Coherence and development efficiency: Planning also improves interactions with APIs by ensuring consistency in the use of endpoints, response types, and formats. Additionally, knowing what the APIs will be used for allows for proper implementation, which reduces development time and the risk of errors.
- Scalability and adaptability : Defining the need for endpoints helps future-proof them to adapt to changing business needs and requirements without the need for a complete redesign.
- safety: Proper endpoint planning helps determine the authentication requirements for accessing or manipulating data. Accessing content through APIs sometimes does not require user authentication. Nevertheless, for content that contains sensitive or unauthorized data, it is important to define security requirements and implement measures such as authorization and access controls to help ensure data security.
The next hands-on section explains how to create custom endpoints that can be used tosite-domain/wp-json/custom/v2/testimonials
Retrieve customer testimonials from the WordPress database site.
After sending the request, the endpoint returns a JSON object containing information about the ratings on the WordPress site as defined in the callback function.
Create custom post types for your endpoints
Create a custom post type first:
1. from the WordPress admin dashboardexterior conditionPartial navigation toTheme File Editor The
2. Open the theme of thefunction.php file and add the following code:
function create_custom_testimonial_type() {
register_post_type('testimonials', array(
'labels' => array(
'name' => 'Testimonials', 'singular_name' =>
'singular_name' => 'Testimonial'.
),
'public' => true,
'has_archive' => true,
'show_in_rest' => true, // This enables REST API support
));
}
add_action('init', 'create_custom_testimonial_type');
This code creates a customized "Recommendation"Post Type and enable WordPress REST API support ( 'show_in_rest' => true
). Callbacksadd_action hook
function (math.)create_testimonial_type
and launch it during execution. Labels and parameters can be customized to suit your needs by removing or adding them.
3. ClickUpdated documents to save the changes.
![图片[3]-为开发人员定制 WordPress:开发定制 REST API 端点-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/04/image-773.png)
Refresh the dashboard to see the WordPress dashboards that have been added to theRecommended Option.
![图片[4]-为开发人员定制 WordPress:开发定制 REST API 端点-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/04/image-774.png)
4. ClickTestimonials > Add New Post Create a new post containing testimonials. You can use thePullquote Blocks. Depending on how you display the recommendations, there are other blocks that can be used.
Here are two sample testimonials created using Pullquote blocks:
![图片[5]-为开发人员定制 WordPress:开发定制 REST API 端点-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/04/image-775.png)
Registering Custom Endpoints in WordPress
Registering a custom endpoint makes it available via the REST API. This involves using theregister_rest_route
function in therest_api_init
call it on a hook and provide a callback method that will be called when the route is invoked.
Paste the following code into the theme'sfunction.php Documentation:
add_action( 'rest_api_init', 'register_testimonial_rest_route' );
function register_testimonial_rest_route(){
register_rest_route(
'custom/v2'.
'/testimonials',
array(
'methods' => 'GET',
'callback' => 'get_testimonials',
)
);
}
theseregister_rest_route()
Three parameters are required:
- routing namespace(
$route_namespace
): This is the first part of the URL segment and should follow the vendor/version number pattern. Vendor stands for vendor or theme slug. namespaces help distinguish endpoints and help customers contact support for your custom endpoints. This tutorial uses thecustom/v2
Namespace. - Basic URL (
$route
): this is located after the namespace and is the URL mapped to the method. you can register multiple endpoints for your route. For the purposes of this article, use the/testimonials
Tells the endpoint to retrieve the recommended route. - Options for endpoints (
$args
): Here is an array of the HTTP methods used when calling the route and the callback function that will be called by the endpoint when the request is sent. We will discuss this callback function in the next section.
Finally, write down the endpoint address. The format of an endpoint issite-address/wp-json/namespace/route
. Thus, in this example, the endpoints will behttps://www.staging.kidspartysanctuary.co.uk/wp-json/custom/v2/testimonials
The
Implementing callback functions for endpoints
After creating a custom post type and registering the custom endpoint, the next step is to write a callback function. This callback function will be called every time the endpoint is accessed.
1,get_testimonials
Use the following code to declare your callback function:
function get_testimonials(){
}
2. Initialize an empty recommendation array to store the retrieved WordPress recommendation data:
$testimonials = array();
3. Set up a$args
An array named after the query parameters forWP_Query
Call.
$args = array(
'post_type' => 'testimonials', //specifies you want to query the custom post type
'testimonials', //specifies you want to query the custom post type
'nopaging' => true, // no pagination, but retrieve all testimonials at once
),
4. Create an instance of the classWP_Query
The instance accepts the array$args
If the query is executed according to the specified parameters and the results of the WordPress query are stored in the$query
in the variable.
$query = new WP_Query($args)
5. Write a conditional statement to check if there are any recommended posts. Then, create awhile
loop to iterate over the posts and return the recommended posts in thetitle
respond in singingcontent
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$testimonial_data = array( /*an array that stores the title
and content of every post*/
'title' => get_the_title(),
// Add other fields as needed
);
$testimonials[] = $testimonial_data;
}
wp_reset_postdata(); /* restores $post
global to the current post to avoid any conflicts in subsequent queries*/
}
return rest_ensure_response( $testimonials ); /*ensures response is
correctly set as a response object for consistency*/ } return rest_ensure_response( $testimonials ); /*ensures response is
6,Using PostmanTest your endpoints to verify that you can access your data.
![图片[6]-为开发人员定制 WordPress:开发定制 REST API 端点-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/04/image-776.png)
It can also be tested using a browser. The test can be performed by using thesite-domain/wp-json/custom/v2/testimonials
Access the endpoint by typing the URL in the address bar of your browser.
![图片[7]-为开发人员定制 WordPress:开发定制 REST API 端点-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/04/image-777.png)
Want to make it easy for users to access and interact with your WordPress database data? Just do one thing: register a route with a callback function. This callback function acts like a little data helper, helping to handle the data when the user wants to access or manipulate it. This way, WordPress API custom endpoints can be implemented without any problem!
Link to this article:https://www.361sale.com/en/8374The article is copyrighted and must be reproduced with attribution.
No comments