0
0
Wordpressframework~5 mins

REST API with JavaScript in Wordpress

Choose your learning style9 modes available
Introduction

A REST API lets your JavaScript code talk to a server to get or send data. This helps your website or app show fresh information without reloading the page.

You want to show the latest blog posts on your site without refreshing.
You need to save user comments or form data to your website.
You want to load images or products dynamically as users browse.
You want to update parts of your page based on user actions.
You want to connect your site to other services or apps.
Syntax
Wordpress
fetch('https://example.com/wp-json/wp/v2/posts')
  .then(response => response.json())
  .then(data => {
    // use the data here
  })
  .catch(error => console.error('Error:', error));
Use fetch to call the REST API URL and get data.
Always handle errors with catch to avoid crashes.
Examples
Get all posts and print them in the browser console.
Wordpress
fetch('https://example.com/wp-json/wp/v2/posts')
  .then(res => res.json())
  .then(posts => console.log(posts));
Get a single post by ID and show its title.
Wordpress
fetch('https://example.com/wp-json/wp/v2/posts/1')
  .then(res => res.json())
  .then(post => console.log(post.title.rendered));
Create a new post by sending data to the API.
Wordpress
fetch('https://example.com/wp-json/wp/v2/posts', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title: 'New Post', content: 'Hello world!' })
})
.then(res => res.json())
.then(data => console.log('Created:', data));
Sample Program

This code fetches the latest blog posts from a WordPress REST API and prints the title of the newest post in the console. It uses modern async/await syntax for clarity and error handling.

Wordpress
const apiUrl = 'https://demo.wp-api.org/wp-json/wp/v2/posts';

async function showLatestPost() {
  try {
    const response = await fetch(apiUrl);
    if (!response.ok) throw new Error('Network response was not ok');
    const posts = await response.json();
    const latest = posts[0];
    console.log(`Latest post title: ${latest.title.rendered}`);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

showLatestPost();
OutputSuccess
Important Notes

Always check if the API URL is correct and accessible.

Use async/await for cleaner and easier-to-read code.

Remember to handle errors to keep your app stable.

Summary

REST API lets JavaScript get or send data to a server without reloading the page.

Use fetch with the WordPress REST API URLs to work with posts, pages, and more.

Handle errors and use async/await for better code.