Bird
Raised Fist0
Wordpressframework~10 mins

REST API with JavaScript in Wordpress - Interactive Code Practice

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using the WordPress REST API with JavaScript?
easy
A. To get or send data to the WordPress server without reloading the page
B. To change the WordPress theme colors
C. To install WordPress plugins automatically
D. To create new WordPress users manually

Solution

  1. Step 1: Understand REST API role

    The REST API allows JavaScript to communicate with the server asynchronously.
  2. Step 2: Identify the purpose in WordPress context

    It is used to get or send data like posts or pages without reloading the page.
  3. Final Answer:

    To get or send data to the WordPress server without reloading the page -> Option A
  4. Quick Check:

    REST API = Data exchange without reload [OK]
Hint: REST API means data exchange without page reload [OK]
Common Mistakes:
  • Thinking REST API changes themes or plugins
  • Confusing REST API with WordPress admin tasks
  • Assuming REST API reloads the page
2. Which of the following is the correct way to fetch posts from the WordPress REST API using JavaScript?
easy
A. fetch('/wp-json/wp/v2/posts').then(response => response.json())
B. fetch('wp-json/wp/v2/posts').json()
C. fetch('/wp-json/wp/v2/posts').json()
D. fetch('/wp-json/wp/v2/posts').then(response => response.text())

Solution

  1. Step 1: Check fetch URL format

    The URL must start with a slash '/' to indicate root path: '/wp-json/wp/v2/posts'.
  2. Step 2: Use correct response method

    Use response.json() inside a then() to parse JSON data correctly.
  3. Final Answer:

    fetch('/wp-json/wp/v2/posts').then(response => response.json()) -> Option A
  4. Quick Check:

    fetch + .then + response.json() = correct syntax [OK]
Hint: Use .then(response => response.json()) after fetch [OK]
Common Mistakes:
  • Missing leading slash in URL
  • Calling .json() directly on fetch without then
  • Using response.text() instead of response.json()
3. What will the following code output if the REST API returns two posts with titles 'Hello' and 'World'?
fetch('/wp-json/wp/v2/posts')
  .then(res => res.json())
  .then(posts => {
    posts.forEach(post => console.log(post.title.rendered));
  });
medium
A. undefined\nundefined
B. posts.forEach is not a function
C. Hello\nWorld
D. Error: Cannot read property 'rendered' of undefined

Solution

  1. Step 1: Understand fetch and JSON parsing

    The fetch gets posts, then res.json() parses the JSON array of posts.
  2. Step 2: Loop through posts and log titles

    posts.forEach logs each post's title.rendered, so it prints 'Hello' and 'World'.
  3. Final Answer:

    Hello\nWorld -> Option C
  4. Quick Check:

    posts.forEach + post.title.rendered = Hello and World [OK]
Hint: Use console.log inside forEach to print each post title [OK]
Common Mistakes:
  • Assuming posts is not an array
  • Forgetting to parse JSON with res.json()
  • Accessing title without .rendered property
4. Identify the error in this code snippet that tries to fetch pages from WordPress REST API:
async function getPages() {
  const response = await fetch('wp-json/wp/v2/pages');
  const data = await response.json;
  console.log(data);
}
medium
A. The function should not be async
B. The fetch URL is missing a leading slash '/' and response.json is missing parentheses
C. console.log should be before fetch call
D. response.json should be replaced with response.text

Solution

  1. Step 1: Check fetch URL format

    The URL 'wp-json/wp/v2/pages' is missing a leading slash '/' which is required for root-relative path.
  2. Step 2: Check response.json usage

    response.json is a function and must be called with parentheses: response.json()
  3. Final Answer:

    The fetch URL is missing a leading slash '/' and response.json is missing parentheses -> Option B
  4. Quick Check:

    URL slash + response.json() needed [OK]
Hint: Always add '/' before REST API path and call .json() as function [OK]
Common Mistakes:
  • Forgetting parentheses on response.json
  • Missing leading slash in URL
  • Misplacing console.log before data is fetched
5. You want to fetch posts and display only those with the word 'JavaScript' in the title using async/await. Which code correctly filters and logs these posts?
hard
A. async function fetchJSPosts() { const res = await fetch('/wp-json/wp/v2/posts'); const posts = await res.text(); const filtered = posts.filter(post => post.title.rendered.includes('JavaScript')); filtered.forEach(post => console.log(post.title.rendered)); }
B. async function fetchJSPosts() { const res = await fetch('/wp-json/wp/v2/posts'); const posts = await res.json; const filtered = posts.filter(post => post.title.includes('JavaScript')); filtered.forEach(post => console.log(post.title.rendered)); }
C. async function fetchJSPosts() { const res = await fetch('/wp-json/wp/v2/posts'); const posts = await res.json(); const filtered = posts.filter(post => post.title.rendered == 'JavaScript'); filtered.forEach(post => console.log(post.title.rendered)); }
D. async function fetchJSPosts() { const res = await fetch('/wp-json/wp/v2/posts'); const posts = await res.json(); const filtered = posts.filter(post => post.title.rendered.includes('JavaScript')); filtered.forEach(post => console.log(post.title.rendered)); }

Solution

  1. Step 1: Correctly fetch and parse JSON

    Use await res.json() to parse the response as JSON array of posts.
  2. Step 2: Filter posts by checking if title.rendered includes 'JavaScript'

    Use posts.filter with post.title.rendered.includes('JavaScript') to select matching posts.
  3. Step 3: Log filtered post titles

    Use forEach to log each filtered post's title.rendered.
  4. Final Answer:

    async function fetchJSPosts() { const res = await fetch('/wp-json/wp/v2/posts'); const posts = await res.json(); const filtered = posts.filter(post => post.title.rendered.includes('JavaScript')); filtered.forEach(post => console.log(post.title.rendered)); } -> Option D
  5. Quick Check:

    await fetch + .json() + filter + includes = async function fetchJSPosts() { const res = await fetch('/wp-json/wp/v2/posts'); const posts = await res.json(); const filtered = posts.filter(post => post.title.rendered.includes('JavaScript')); filtered.forEach(post => console.log(post.title.rendered)); } [OK]
Hint: Use .json() and filter with includes() on title.rendered [OK]
Common Mistakes:
  • Forgetting parentheses on json()
  • Using == instead of includes for substring
  • Parsing response as text instead of JSON
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard