0
0
Wordpressframework~10 mins

REST API with JavaScript in Wordpress - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to fetch posts from the WordPress REST API.

Wordpress
fetch('https://example.com/wp-json/wp/v2/posts')
  .then(response => response.[1]())
  .then(data => console.log(data));
Drag options to blanks, or click blank then click option'
Atext
Bhtml
Cblob
Djson
Attempts:
3 left
💡 Hint
Common Mistakes
Using text() instead of json() causes data to be a string, not an object.
2fill in blank
medium

Complete the code to handle errors when fetching posts.

Wordpress
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));
Drag options to blanks, or click blank then click option'
Ajson
Bblob
Ctext
Dhtml
Attempts:
3 left
💡 Hint
Common Mistakes
Parsing response before checking response.ok can cause errors.
3fill in blank
hard

Fix the error in the code to correctly fetch a single post by ID.

Wordpress
const postId = 5;
fetch(`https://example.com/wp-json/wp/v2/posts/[1]`)
  .then(res => res.json())
  .then(post => console.log(post));
Drag options to blanks, or click blank then click option'
A{postId}
BpostId
C${postId}
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable name without ${} inside template literals results in a string literal.
4fill in blank
hard

Fill both blanks to create a POST request to add a new post with JSON data.

Wordpress
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));
Drag options to blanks, or click blank then click option'
APOST
BGET
Capplication/json
Dtext/plain
Attempts:
3 left
💡 Hint
Common Mistakes
Using GET method or wrong content type causes the request to fail.
5fill in blank
hard

Fill all three blanks to update a post's title using the PATCH method.

Wordpress
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));
Drag options to blanks, or click blank then click option'
ApostId
BPATCH
Capplication/json
DPUT
Attempts:
3 left
💡 Hint
Common Mistakes
Using PUT instead of PATCH or missing content type header.