I am trying to filter by a meta query but no matter what I try I can not make it work.
Basically I want this query in through the rest API:
wp-json/wp/v2/books?meta_query[relation]=OR&meta_query[0][key]=arkivera&meta_query[0][value]=1&meta_query[0][compare]==
Ive tried several different custom fields but it will always return all post objects.
In my functions file I’ve added:
function api_allow_meta_query( $valid_vars ) {
$valid_vars = array_merge( $valid_vars, array( 'meta_query') );
return $valid_vars;
}
add_filter( 'rest_query_vars', 'api_allow_meta_query' );
I tried finishing some documentation regarding this but couldn’t, also most of the similar questions are not for wordpress 4.7 since filter[xxx] is removed.
You can write your own REST handler for custom queries if you want. In your case, the query can done by doing so:
// Register a REST route
add_action( 'rest_api_init', function () {
//Path to meta query route
register_rest_route( 'tchernitchenko/v2', '/my_meta_query/', array(
'methods' => 'GET',
'callback' => 'custom_meta_query'
) );
});
// Do the actual query and return the data
function custom_meta_query(){
if(isset($_GET['meta_query'])) {
$query = $_GET['meta_query'];
// Set the arguments based on our get parameters
$args = array (
'relation' => $query[0]['relation'],
array(
'key' => $query[0]['key'],
'value' => $query[0]['value'],
'compare' => '=',
),
);
// Run a custom query
$meta_query = new WP_Query($args);
if($meta_query->have_posts()) {
//Define and empty array
$data = array();
// Store each post's title in the array
while($meta_query->have_posts()) {
$meta_query->the_post();
$data[] = get_the_title();
}
// Return the data
return $data;
} else {
// If there is no post
return 'No post to show';
}
}
}
Now, all you have to do is to access:
wp-json/tchernitchenko/v2/my_meta_query?meta_query[relation]=OR&meta_query[0][key]=arkivera&meta_query[0][value]=1&meta_query[0][compare]==