Discover in this tutorial how to extract the number of posts from a Custom Post Type using the WordPress REST API.
One of the advantages of being an OsomCode subscriber is that you can make suggestions for future tutorials.
Following the tutorial on how to show the number of “parent” entries of a CPT dynamically with a shortcode, a susbscriber asked me the following question:
Hi, Nahuai.
Thank you very much for the post. It’s great.
I am thinking if there is a possibility to do the same but with the CPT of another website. Is this possible?
Thank you very much in advance.
As I told her, the WordPress REST API allows you to know the number of posts of a Custom Post Type within any WordPress website.
And in this tutorial I’m going to show you how to put it into practice.
Code to get the number of entries of a Custom Post Type using the REST API
The code you need to access the number of entries of a Custom Post Type is the following:
To see this and another 1097 code snippets of this website, login or subscribe here.
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 stores the value you are interested in.
To adapt this snippet to your convenience:
- Replace the URL (yourwebsite.com) with the URL of the site from which you want to retrieve the number of posts.
- Replace “lesson” with the Custom Post Type you want to query.
For example? You can do the test with osomcode.com as URL and you will see that you get the same number of tutorials that I indicate in the home page. 😉
In this case, I have placed an echo
at the end to display the number. But you can take the value of that variable and display it using a shortcode as we 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.
Conclusion
Thanks to the REST API you can get the number of posts of a Custom Post Type of any WordPress (that does not 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. 😉