Complete the code to fetch posts from the WordPress REST API.
fetch('https://example.com/wp-json/wp/v2/posts') .then(response => response.[1]()) .then(data => console.log(data));
The json() method parses the response body as JSON, which is the format WordPress REST API returns.
Complete the code to handle errors when fetching posts.
fetch('https://example.com/wp-json/wp/v2/posts') .then(response => { if (!response.ok) throw new Error('Network error'); return response.[1](); }) .catch(error => console.error(error));
We still parse the response as JSON after checking if the response is OK.
Fix the error in the code to correctly fetch a single post by ID.
const postId = 5; fetch(`https://example.com/wp-json/wp/v2/posts/[1]`) .then(res => res.json()) .then(post => console.log(post));
Inside template literals, variables must be wrapped in ${} to be evaluated.
Fill both blanks to create a POST request to add a new post with JSON data.
fetch('https://example.com/wp-json/wp/v2/posts', { method: '[1]', headers: { 'Content-Type': '[2]' }, body: JSON.stringify({ title: 'New Post' }) }) .then(res => res.json()) .then(data => console.log(data));
To create a new post, the HTTP method must be POST and the content type must be application/json.
Fill all three blanks to update a post's title using the PATCH method.
const postId = 10; fetch(`https://example.com/wp-json/wp/v2/posts/$[1]`, { method: '[2]', headers: { 'Content-Type': '[3]' }, body: JSON.stringify({ title: 'Updated Title' }) }) .then(res => res.json()) .then(data => console.log(data));
Use the variable postId inside the URL, the PATCH method to update partially, and set content type to application/json.