0
0
Wordpressframework~30 mins

REST API with JavaScript in Wordpress - Mini Project: Build & Apply

Choose your learning style9 modes available
REST API with JavaScript in WordPress
📖 Scenario: You are building a simple WordPress site feature that fetches and shows the latest blog posts using the WordPress REST API and JavaScript.
🎯 Goal: Create a JavaScript script that fetches the latest 3 posts from the WordPress REST API and displays their titles in a list on the webpage.
📋 What You'll Learn
Use the WordPress REST API endpoint /wp-json/wp/v2/posts
Fetch exactly 3 posts
Display the post titles inside an unordered list <ul>
Use modern JavaScript with fetch and async/await
Add a container <div id="post-list"> in HTML to show the posts
💡 Why This Matters
🌍 Real World
Fetching and showing WordPress posts dynamically helps keep your site content fresh without manual updates.
💼 Career
Understanding how to use REST APIs with JavaScript is essential for modern web development and integrating with platforms like WordPress.
Progress0 / 4 steps
1
HTML Setup for Post List Container
Create a div element with id="post-list" in the HTML body where the post titles will appear.
Wordpress
Need a hint?

Use a div tag with the exact id="post-list" inside the body.

2
Set the API Endpoint URL
In a new <script> tag before the closing </body>, create a constant variable called apiUrl and set it to the string "https://example.com/wp-json/wp/v2/posts?per_page=3".
Wordpress
Need a hint?

Use const apiUrl = "https://example.com/wp-json/wp/v2/posts?per_page=3"; inside a <script> tag.

3
Fetch Posts and Extract Titles
Inside the <script> tag, write an async function called loadPosts that uses fetch(apiUrl) and await to get the response. Then convert the response to JSON and store it in a variable called posts. Use a for...of loop with post to iterate over posts and create an array called titles containing each post's title.rendered.
Wordpress
Need a hint?

Use async function loadPosts(), await fetch(apiUrl), and a for...of loop to fill titles with post.title.rendered.

4
Display Titles in the HTML List
Still inside the loadPosts function, select the div with id="post-list" into a variable called postList. Create a string variable html that starts with "
    ". Use a for...of loop with title over titles to add each title inside <li> tags to html. After the loop, add "
" to html. Finally, set postList.innerHTML = html. Call loadPosts() after the function definition.
Wordpress
Need a hint?

Use document.getElementById("post-list"), build html string with <ul> and <li>, then set postList.innerHTML. Call loadPosts() to run.