Turns out i had to add this to the functions.php file.
// MAKE API FILTERABLE
add_action( 'rest_api_init', 'post_meta_register' );
function post_meta_register() {
register_api_field( 'post',
'testing',
array(
'get_callback' => 'get_post_meta',
'update_callback' => null,
'schema' => null,
)
);
}
function get_post_meta( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], $field_name, true );
}
add_filter( 'rest_query_vars', 'allow_meta' );
function allow_meta( $valid_vars ) {
$valid_vars = array_merge( $valid_vars, array( 'meta_key', 'meta_value' ) );
return $valid_vars;
}
Just want to add that, like Martin, the code on GitHub didn’t work for me either, but Martin’s code in his 2nd post did. Thanks Martin!
I’m using a custom post type, so if you are too, in the post_meta_register function be sure to change ‘post’ to your post type name, and of course, change ‘testing’ to the name of your ACF field.
I also had to rename the functions themselves as they were causing conflicts, but other than that everything now works as expected.
I just stumbled across this, and it took a bit of tweaking, figured I’d share what I had to do to get it working:
note the change to register_rest_field
– register_api_field
is deprecated.
add_action( 'rest_api_init', 'post_meta_register' );
function post_meta_register() {
register_rest_field( 'post',
'ACF_FIELD_NAME_HERE',
array(
'get_callback' => 'get_acf_post_meta',
'update_callback' => null,
'schema' => null,
)
);
}
function get_acf_post_meta( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], $field_name, true );
}
add_filter( 'rest_query_vars', 'allow_meta' );
function allow_meta( $valid_vars ) {
$valid_vars = array_merge( $valid_vars, array( 'meta_key', 'meta_value' ) );
return $valid_vars;
}
Edit: I moved all of this out of functions.php
and into a standalone plugin file so that I (hopefully) won’t have problems with future updates to WordPress. If you want to put this code into functions.php
you may need to edit wp-settings.php
to require plugin.php
before functions.php
so that add_action(0
and add_filter()
are defined before you try to use them.