WordPress REST API post orderby custom value

tl;dr: Ordering posts by menu_order doesn’t work out of the box with the WP REST API. To enable this you need to add a filter to rest_{post_type}_collection_params for each post type you want to order by menu_order.

The WP REST API is a great addition to WordPress, made even better in v2. It enables us to do some great things with Javascript on the front end of the site, and also gives a great way of doing batch updates, from scripts and other serverside code outside the wordpress environment.

In a recent project I needed to display the posts from the REST API in a custom order. This is not possible in on custom post types normally, so I installed a plugin to do the work in the admin area for me. Simple Custom Post Order allows you to drag and drop the order of the posts in the admin view. This is exactly what I needed.

Behind the scenes in the database, the plugin updates the column menu_order in the posts table. So to display the posts in the custom order in the front end, the WP_Query needs to have an orderby parameter set to menu_order. Easy if you are building a WP_Query directly. Its not so easy in the REST API though, there is an orderby parameter enabled for the WP REST API, but by default, the only values you can sort by are: author, date, id, include, modified, parent, relevance, slug, include_slugs, title.

If you try to orderby another value, then you get an error from the REST API:

  "code": "rest_invalid_param",
  "message": "Invalid parameter(s): orderby",
  "data": {
    "status": 400,
    "params": {
      "orderby": "orderby is not one of author, date, id, include, modified, parent, relevance, slug, include_slugs, title."

Luckily there is a WordPress filter that allows you to modify this list of values and orderby anything you want. The filter hook is called rest_{post_type}_collection_params. You can see how to use it in the following gist:

With this filter enabled, now you can make a request to the WP REST API and get the posts back in exactly the order you need. No more rest error messages.


And the posts should be listed exactly as they are defined in the admin area.

One thought on “WordPress REST API post orderby custom value

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.