Are you trying to retrieve all posts from a given category in wordpress using the wordpress API? Do you need to get more than 10 posts from a post category when using the wordpress api? In this post, we’ll cover how to get all posts in a category using the wordpress api and python.
Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!
The answer is the posts api endpoint, https://example.com/wp-json/wp/v2/posts, in conjunction with the per_page and categories arguments. per_page specifies the number of posts to return in the resulting response, while categories is the numeric category id for which you want to retrieve the data.
Because the default per_page is 10, you will want to increase this to exceed the number of posts available in the category. For example, if my category has 73 posts and id 13, I can retrieve all posts using the following:
resp = requests.get("https://example.com/wp-json/wp/v2/posts?categories=13&per_page=100")
How to find the numeric id for a wordpress category?
You can find the numeric id associated with your category by editing the category from your wp dashboard, and checking the tag_ID=1440 in the url (in this case 1440 is the id associated with the category).
If you don’t have access to the WP dashboard, you can also use a script if you know the category name (i.e top-ten) to get the id:
If you don’t know how many posts are in the category, you will need to iteratively request incrementing page values until the returned json array contains no more members.