Consider this JavaScript code snippet in a WordPress theme fetching posts via REST API:
fetch('https://example.com/wp-json/wp/v2/posts')
.then(response => response.json())
.then(data => console.log(data.length))
.catch(error => console.error('Error:', error));What will be logged to the console if the site has 5 published posts?
fetch('https://example.com/wp-json/wp/v2/posts') .then(response => response.json()) .then(data => console.log(data.length)) .catch(error => console.error('Error:', error));
Think about what the REST API returns and what data.length means.
The WordPress REST API returns an array of post objects. The data.length gives the number of posts fetched. Since there are 5 posts, it logs 5.
You want to fetch a post with ID 10 from the WordPress REST API using async/await syntax. Which code snippet is correct?
Remember that await must be used with promises and inside async functions.
Option A correctly awaits both the fetch and the JSON parsing. Option A is not async but uses await, Option A misses awaits, and D misses awaiting response.json().
This code tries to fetch posts from a WordPress REST API but fails with a CORS error in the browser console:
fetch('https://anotherdomain.com/wp-json/wp/v2/posts')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));What is the most likely reason for the CORS error?
Think about browser security rules for cross-site requests.
CORS errors happen when the server does not send headers allowing your site to access its resources. The URL might be correct, and fetch supports GET by default. The browser supports fetch, so the issue is server-side CORS policy.
In a React component, this code fetches posts and sets state:
const [posts, setPosts] = React.useState([]);
React.useEffect(() => {
fetch('https://example.com/wp-json/wp/v2/posts')
.then(res => res.json())
.then(data => setPosts(data))
.catch(() => setPosts([]));
}, []);If the fetch succeeds and returns 3 posts, what will posts.length be after the effect runs?
const [posts, setPosts] = React.useState([]);
React.useEffect(() => {
fetch('https://example.com/wp-json/wp/v2/posts')
.then(res => res.json())
.then(data => setPosts(data))
.catch(() => setPosts([]));
}, []);Consider what happens when the fetch is successful and how state updates.
The fetch returns an array of 3 posts, which is set as the new state. So posts.length becomes 3.
You want to create a new post on a WordPress site using the REST API and JavaScript. Which HTTP method and header must you include in your fetch request?
Think about how to send data securely and the method used to create resources.
Creating a post requires a POST request with JSON data, so the 'Content-Type: application/json' header is needed. Also, WordPress requires authentication, so an Authorization header with a valid token is necessary.