The rest_do_request() WordPress PHP function performs a REST request, primarily used for routing internal requests through WP_REST_Server.
Usage
$result = rest_do_request( $request );
Example:
$request = new WP_REST_Request( 'GET', '/wp/v2/posts' ); $result = rest_do_request( $request );
Parameters
$request(WP_REST_Request|string) – Required. The REST request object or request string to be performed.
More information
See WordPress Developer Resources: rest_do_request()
Examples
Get all posts
Retrieve all published posts.
// Create a REST request for all posts
$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );
// Perform the request
$result = rest_do_request( $request );
// Print the titles of all posts
foreach ( $result->data as $post ) {
echo $post['title']['rendered'] . '<br>';
}
Get a specific post by ID
Retrieve a post by its ID.
$post_id = 10; // Replace with a valid post ID // Create a REST request for the post with the given ID $request = new WP_REST_Request( 'GET', "/wp/v2/posts/$post_id" ); // Perform the request $result = rest_do_request( $request ); // Print the post title echo $result->data['title']['rendered'];
Create a new post
Create a new post with a title and content.
// Set post data
$post_data = array(
'title' => 'My New Post',
'content' => 'This is the content of my new post.',
'status' => 'publish'
);
// Create a REST request to create a new post
$request = new WP_REST_Request( 'POST', '/wp/v2/posts' );
$request->set_body_params( $post_data );
// Perform the request
$result = rest_do_request( $request );
// Print the ID of the newly created post
echo 'New post created with ID: ' . $result->data['id'];
Update a post’s title
Update the title of a post by its ID.
$post_id = 10; // Replace with a valid post ID // Set new post title $new_title = 'Updated Post Title'; // Create a REST request to update the post's title $request = new WP_REST_Request( 'POST', "/wp/v2/posts/$post_id" ); $request->set_body_params( array( 'title' => $new_title ) ); // Perform the request $result = rest_do_request( $request ); // Print the updated post title echo 'Post title updated to: ' . $result->data['title']['rendered'];
Delete a post
Delete a post by its ID.
$post_id = 10; // Replace with a valid post ID // Create a REST request to delete the post with the given ID $request = new WP_REST_Request( 'DELETE', "/wp/v2/posts/$post_id" ); $request->set_query_params( array( 'force' => true ) ); // Perform the request $result = rest_do_request( $request ); // Print a confirmation message echo 'Post with ID ' . $result->data['id'] . ' has been deleted.';