DEV Community

Cover image for NPM Library to get a list of WordPress posts' character counts using the WP REST API
Yuki Shindo
Yuki Shindo

Posted on

NPM Library to get a list of WordPress posts' character counts using the WP REST API

NPM Library to get a list of WordPress posts' character counts

I have created an npm library to retrieve the character count of all articles published on WordPress using the REST API provided by WordPress.
The name is wp-rest-api-posts-wordcount.

Check the GitHub repository for details.
https://github.com/shinshin86/wp-rest-api-posts-wordcount

Installation and code examples are as follows.

Install:

npm install wp-rest-api-posts-wordcount
# or
yarn add wp-rest-api-posts-wordcount
Enter fullscreen mode Exit fullscreen mode

Example:

const getWordcountList = require('wp-rest-api-posts-wordcount');

(async () => {
  try {
    const response = await getWordcountList('your wordpress url');
    console.log(response);
  } catch (e) {
    console.error(e);
  }
})();
Enter fullscreen mode Exit fullscreen mode

What is WP REST API?

To briefly explain the WP REST API used in this library, WordPress provides the following endpoints for REST APIs.

https://developer.wordpress.org/rest-api/

This can be disabled on the WordPress side, but is probably currently enabled by default if you have not made any changes to your settings.

This REST API can be used to retrieve information about published articles.

For example, you can check the value x-wp-total in the response header to get the number of target WordPress pages, etc.
You can use it in various ways, so it would be interesting to read this document once.
(I actually use x-wp-total in my npm library)

Code sample using WP REST API

Here is where the WP REST API is actually used in wp-rest-api-posts-wordcount.

This shows that it is very easy to use the WP REST API.

const targetUrl = `${url}/wp-json/wp/v2/posts`;
const response = await fetch(targetUrl);
const wpTotalPageCount: number = response.headers.get('x-wp-total');
Enter fullscreen mode Exit fullscreen mode

It is possible to retrieve information about public posts by sending a request to the endpoint your_wordpress_url/wp-json/wp/v2/posts like this.

response.headers.get('x-wp-total') to get the number of pages in WordPress.

From this sample, you can see that this API is easy to use.

Various information can be found by checking the official documentation.

Let's build all sorts of useful tools using the WP REST API!

Top comments (0)