Search code examples
wordpress-rest-api

How to get posts orderby comment_count ascending and where to place the code? (Wordpress REST API)


I am a complete beginner when it comes to extending Wordpress REST API. I need to extend the API so that a request to /wp-json/wp/v2/posts?orderby=comment_count&order=asc would yield a response with posts that are ordered by comment count in ascending order ie. posts with the least amount of comments appear first.

I skimmed through the REST API Handbook and watched a couple of YouTube videos, but found no answer to my problem. I found this answer and it looks promising, however I'm not entirely sure if the code provided there fits my needs. From what I could gather WP_Query class is what I'm looking for, but I don't know how to make use of it. My second problem is that I don't know where exactly to place any code I may have stumbled upon ie. which file is supposed to play host to the code eventually?

I would greatly appreciate detailed answers and possibly sources for more information regarding this topic.


Solution

  • According to WordPress documentation orderby only accept following parameters: author, date, id, include, modified, parent, relevance, slug, include_slugs, title

    But you can add custom parameters to orderby if you have access to Wordpress website code. Please follow the below URL:

    https://www.timrosswebdevelopment.com/wordpress-rest-api-post-order/

    Let me know if you need more help.