Skip to content

Instantly share code, notes, and snippets.

@corsonr
Created December 2, 2022 11:08
Show Gist options
  • Save corsonr/292f0fbf118479d5063d858128d002f5 to your computer and use it in GitHub Desktop.
Save corsonr/292f0fbf118479d5063d858128d002f5 to your computer and use it in GitHub Desktop.
Introduction to the WordPress Rest API
<?php
// Set the endpoint and request method
$endpoint = '/wp/v2/posts';
$method = 'POST';
// Set the request body data
$body = array(
'title' => 'My new post',
'content' => 'This is the content of my new post.',
'status' => 'publish',
);
// Make the HTTP request
$response = wp_remote_request($endpoint, array(
'method' => $method,
'body' => $body,
));
// Check the response and handle any errors
if (is_wp_error($response)) {
// There was an error making the request
echo 'Error: ' . $response->get_error_message();
} else {
// The request was successful
$response_body = json_decode($response['body'], true);
echo 'Post created: ' . $response_body['title']['rendered'];
}
<?php
// Create a new class that extends the WP_REST_Controller class
class Posts_By_Author_Controller extends WP_REST_Controller {
// Register the routes and methods for the endpoint
public function register_routes() {
$route = '/wp/v2/posts/by_author/(?P<author_id>\d+)';
$args = array(
'methods' => 'GET',
'callback' => array($this, 'get_posts_by_author'),
);
register_rest_route('my-plugin/v1', $route, $args);
}
// Define the method that handles the request and response for the endpoint
public function get_posts_by_author($request) {
$author_id = (int) $request['author_id'];
// Query the database for posts by the specified author
$posts = get_posts(array(
'author' => $author_id,
));
// Return the posts as a JSON object
$response = new WP_REST_Response($posts);
$response->set_status(200);
return $response;
}
}
// Register the custom endpoint with the WordPress API
add_action('rest_api_init', function() {
$controller = new Posts_By_Author_Controller();
$controller->register_routes();
});
<?php
// Set the endpoint and request method
$endpoint = '/wp/v2/posts/123'; // Replace 123 with the ID of the post you want to retrieve
$method = 'GET';
// Make the HTTP request
$response = wp_remote_request($endpoint, array(
'method' => $method,
));
// Check the response and handle any errors
if (is_wp_error($response)) {
// There was an error making the request
echo 'Error: ' . $response->get_error_message();
} else {
// The request was successful
$response_body = json_decode($response['body'], true);
echo 'Post retrieved: ' . $response_body['title']['rendered'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment