person holding white printer paper

WordPress REST API. Sorting/Orderby for custom meta fields in WordPress and fixing “Invalid parameter(s): orderby”

Why?

By default in WordPress you can only use the valid fields which are specified by each post type. Read more on WordPresss REST API documentation.

This post is useful to you if you might be receiving an error as following.

code“rest_invalid_param”
message“Invalid parameter(s): orderby”
rest_invalid_param – error you receive when you put a custom meta field on order by.

How can you check which fields are available ?

REST API http://yoursite.com/wp-json/

The above URL on your WordPress website gives you all the routes and here you can also find all the valid fields for orderby parameter you can send while requesting data through REST calls.

Example to check available orderby fields for posts content type.

Example of how you will find all the fields available for post type = posts.
Check the JSON on the following node.

Inside you will find all the fields like the screenshot pasted below.

Similar how we see the the available fields for the posts type we can also see the fields available for other content types.

💡 Tip

If you open the link in Firefox it will give you a hierarchical navigation like below whereas Chrome just throws raw JSON which is difficult to read without a JSON Parser such as this one http://json.parser.online.fr/ you might have to paste the raw JSON content to read it properly.

Making our custom fields available for the REST API order by.

We would need to add some code to functions.php either inside your plugin or theme.

To make our custom field available we will use two filters

  1. ‘rest_’ . $post_type . ‘_collection_params’
    We will use to add our custom fields to the allowed list of fields.
  2. ‘rest_’ . $post_type . ‘_query
    Will use to add the order by functionality when our API is called.

Add the following code and replace “wf_account” with your own post type.
And fields with your own fields.

Once you do so you would be able to see the new fields available and the error will go away. .

The second step is to make the orderBy Work for your fields add the following code.

Once you add these two functions your sorting will start working.

Initiating the function only when REST API is used.

Well we don’t need these functions to load up when the normal WordPress is being used so we will call them when REST API is used using action rest_api_init. this will keep our code optimized.

Here is the complete example

That’s it. If you