admin管理员组

文章数量:1124168

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?

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?

Share Improve this question asked Mar 22, 2019 at 1:14 Lai32290Lai32290 3511 gold badge4 silver badges15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 4

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 );

本文标签: metaboxHow to search by metadata using REST API