How to enable 'meta_key' option for wordpress REST api filter

I’m working at a project which is using wordpress as the backend management system. WP has a great rest api plugin . However, the filter options are limited. Unfortunately, ‘meta_key’ is not supported in current version.

I’ve spent several hours to investigate this plugin, and finally found a one-line-code solution:

  1. Find a line in get_posts function:
// Allow the same as normal WP
$valid_vars = apply_filters('query_vars', $wp->public_query_vars);
  1. Add following code below it:
// Add additional key to support.
array_push($valid_vars, 'meta_key');

Done :)

Additionally, add more custom field support you need:

// Add additional custom field keys to support.
array_push($valid_vars, 'meta_key');
array_push($valid_vars, 'meta_value');
array_push($valid_vars, 'meta_value_num');
array_push($valid_vars, 'meta_compare');
array_push($valid_vars, 'meta_query');
Written on August 10, 2014