1

I have a custom post type like this:

register_post_type('horario_busao', [
    'labels' => [
        'name' => 'Horário Busões',
        'singular_name' => 'Horário Busão'
    ],
    'public' => true,
    'has_archive' => true,
    'show_in_rest' => true
]);

And it contains a metadata city, which I update it this way:

return update_post_meta($postId, 'city', $city);

So I'm fetching it by the endpoint /wp-json/wp/v2/horario_busao. As I see in the documentation, it only contain the query param search.

How can I search it by metadata?

2

How can I search it by metadata?

As far as I know, there's no standard/built-in way of doing that (for the time being). But with custom coding, you can make it possible:

You can append a city to the query string:

/wp-json/wp/v2/horario_busao?city=London

And then use the rest_{$this->post_type}_query filter to set the meta key/value pair which would be passed to WP_Query. Here's an example:

add_filter( 'rest_horario_busao_query', function( $args, $request ){
    if ( $city = $request->get_param( 'city' ) ) {
        $args['meta_key'] = 'city';
        $args['meta_value'] = $city;
    }
    return $args;
}, 10, 2 );
  • Wow! it just works!! thank you so much – Lai32290 Mar 22 '19 at 11:21
  • Is the $args a object like WP_Query? can I filter by multiple metadata? – Lai32290 Mar 22 '19 at 11:23
  • 1
    Yes, the $args is the same parameters you would use when making post queries using new WP_Query( $args ) or get_posts( $args ). So you can use the meta_query parameter to make multiple meta queries - or to filter by multiple metadatas. (Btw, sorry for the late reply..) – Sally CJ Mar 23 '19 at 2:24
  • Thank you for the clean explanation! – Lai32290 Mar 23 '19 at 12:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.