Get Recent Posts using Vanilla JavaScript - WP REST API
Get Recent Posts using Vanilla JavaScript and WordPress REST API is simple and could be done without using JavaScript libraries, frameworks and PHP plugins.
We'll use WordPress as back-end Content Management System and we'll create independently our own simple theme /front-end/. For back-end we'll use WordPress 5.2.2, built in endpoints and standard theme Twenty Seventeen. It is installed in the domain W3Design.mobi.
The exact WP REST API request is done through
GET /wp-json/wp/v2/posts
and uses the built in the WordPress kernel endpoint.
The last 10 posts will be returned. We only want to show 3, so we will use per_page = 3 as follows:
GET /wp-json/wp/v2/posts?per_page=3
In our case it will look like this:
https://earth-for-all.com/twentyseventeen/wp-json/wp/v2/posts?per_page=3
We need of a sample HTML page with one container: section class="content". We will display the contents of posts in it.
The file get-recent-posts.js is included in the end of the page. This file contain pure Vanilla JavaScript code.
Get Recent Posts using WordPress REST API, AJAX and vanilla JavaScript
Let's write the code for the request that will extract the content of recent posts. We'll use a standard AJAX request with addition of several rows ( window.ActiveXObject ....) that allow it to be executed by older versions of Internet Explorer.
We’ll declare the following variables into the get-recent-posts.js file:
wpThemeURL - the path to WordPress Backend Theme, that initiate the posts. In this case we use Twenty Seventeen;
per_page - the number of posts we want to receive.
The result from request – the JSON file will include the contents of the last three posts:
It only remains to read this JSON file and display it to screen.
Get Recent Posts using Vanilla JavaScript, JSON and WP REST API
We'll do it by function parseLastPostsResponse, that contains the following code:
You can see the live demo of this working example here and the same information from the backend theme Twenty Seventeen here.
This example is a part from Elf - WordPress REST API Starter Theme, which has a FREE version developed using pure vanilla JavaScript code.
Look at the Elf - WP REST API Theme DEMO ! Download FREE VERSION of Elf-WP REST API Theme !Have a good time and create useful and beautiful WordPress sites and applications with Elf - WP REST API Theme. Good luck!