wp-net / WordPressPCL

This is a portable library for consuimg the WordPress REST-API in (almost) any C# application
MIT License
337 stars 129 forks source link

Any way to get total posts count? #255

Open proleskovskiy opened 3 years ago

proleskovskiy commented 3 years ago

Hello!

According to the official docs: https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/

"To determine how many pages of data are available, the API returns two header fields with every paginated response: X-WP-Total: the total number of records in the collection X-WP-TotalPages: the total number of pages encompassing all available records"

I query posts using await client.Posts.Query(query), with 'Page' and 'PerPage' parameters set, but this method only returns posts. Is there a way to get total posts count without actually loading all of them with client.Posts.GetAll()?

ThomasPe commented 3 years ago

I agree that this would be a useful addition, I'll add it to the backlog.

marinasundstrom commented 3 years ago

Perhaps, instead of returning an IEnumerable for Queries, return a custom collection with additional properties related to the response, including the page count. It will, of course, still be enumerable.

class PostQueryResult : QueryResult<Post> 
{

}

class QueryResult<T> : IEnumerable<T> 
{
    public int TotalPages { get; }
}
marinasundstrom commented 3 years ago

My prototype: https://github.com/robertsundstrom/WordPressPCL/tree/queryresult

I created the QueryResult class, and substituted the return type of Query (IEnumerable) with it. It would not be a big deal since QueryResult is implementing IEnumerable.

The added properties of QueryResult are Total and TotalPages.

marinasundstrom commented 3 years ago

Pull request: https://github.com/wp-net/WordPressPCL/pull/257

marinasundstrom commented 3 years ago

I have published a sample app here:

https://github.com/robertsundstrom/headless-wordpress-blazor

The Frontend project contains a build of WordPressPCL.

ThomasPe commented 3 years ago

Hey, thanks so much for your work. I'll try to check it out on the weekend!

delasource commented 1 year ago

please check this. i'm looking for an easy way of pagination to get all items (not just Posts but custom object types)

An easy way would be just to expose HttpClient.LastResponseHeaders publicly. (of course this may not be the best thread-safe solution)