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

How to get all posts by a given author? #204

Closed navjot50 closed 4 years ago

navjot50 commented 4 years ago

I want to get all the posts that are created by a given author. The function GetPostsByAuthor in the Posts class just gives the the first 10 posts by a given author. Also the method GetAll which the Posts class inherits from CRUDOperation class gets all the posts regardless of any filtering on the basis of author id.

Another thing is that we cannot get the response headers as the requests are executed internally by the HttpHelper classes, so there is no way to determine how many X-WP-TotalPages are there.

One ugly workaround that i found out is:

` public async Task<List> GetAllPostsForGivenAuthor(int authorId) { int pageNum = 1; var postQueryBuilder = new PostsQueryBuilder() { Page = pageNum, PerPage = Constants.WordpressConstants.PerPage, //this is a constant value in my project Authors = new int[] { authorId }, OrderBy = PostsOrderBy.Date };

  var postsByAuthor = new List<Post>();
  while (true) {
    try {
      var queryResult = await wordpressRestClient.Posts.Query(postQueryBuilder);
      postsByAuthor.AddRange(queryResult.ToList());
      postQueryBuilder.Page = ++pageNum;
    } catch (WPException) {
      break;
    }
  }

  return postsByAuthor;

} ` I don't like the fact that we have a while loop on true and that we have to expect an exception to break the loop. Is there a better way to do this?