Discover in this tutorial how to get the number of posts in a WordPress blog using the WordPress REST API.
In previous tutorials you have seen how to display the number of posts of your website (or your client) dynamically.
But what if you have two related websites and you want to display the number of posts of one on the other?
Well, nothing happens, because in WordPress you have the fantastic REST API that allows you to know the number of entries of any website that has this API active (which are most WordPress installations).
And in this tutorial you will learn how to access this data.
Code to get the number of posts using the WordPress REST API
The code you need to access the number of posts is as follows:
In this block you use the
wp_remote_get function to get the data from the URL accessed by the REST API. And with
wp_remote_retrieve_header you tell it to take the argument
x-wp-total, which is the one that stores the value you are interested in.
To adapt this snippet to your convenience you only have to replace the URL (yourwebsite.com) by the one of the site from which you want to take the number of entries.
If you want you can do the test by putting osomcode.com in the URL and you will see how you get the same number of tutorials that I indicate in the home page. 😉
In this case, you will see that there is an
echo at the end of the code to display the number. But you can take the value of that variable and display it using a shortcode as you have seen in other tutorials.
If you have doubts about how to do it just let me know and I will prepare a custom tutorial. 😉
Thanks to the REST API you can get the number of posts from any WordPress (that doesn’t have the API disabled) and display it wherever you want.
Any questions? I read you in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉