TransWikia.com

rest api request including meta_query filter

WordPress Development Asked on January 2, 2022

I’m creating a web service using the WP REST API v.2.
Is it possible to include something like a meta_query filter when requesting a custom post type?

For example, if I was using WP_Query, I could do this:

$args = array(
    'post_type'         => 'proposal',
    'posts_per_page'    => -1,
    'meta_query'    => array(
        array(
            'key'       => 'deadline',
            'value'     => current_time( 'm/d/Y' ),
            'compare'   => '>=',
        )
    )
);

$proposals_query = new WP_Query( $args );

Is it possible to accomplish the same thing in a REST request?
The example goal would be to let the service know that the client wants a response that only includes posts that meet the meta_query conditions.
I guess I could send a variable in the request and use that to build a meta_query in a custom endpoint…? So I’m wondering if there is some recommended way to proceed.

One Answer

Maybe not exactly the answer you are looking for, but here it goes....

The rest API as it is implemented in wordpress core is a mockery of how APIs should be designed and the less you use it the better. Obviously it will be just stupid to not use a core API that does exactly what you need, but for anything else you should just write your own APIs.

The rest API is designed as a remote call to execute internal APIs, instead of performing a very specific action. This leads to two big problems

  1. Information leakage. The API returns much more then what you need and some of the information it returns should not be returned at all due to privacy and security concerns. If I know what is the author ID and your WP version and plugins I might be able to craft an attack on your site.

  2. Non optimal data structure that might lead you to make two DB queries on the server side, will lead you into doing two http requests, something that takes much more time and increases the server load. You could see it (I just hope they fixed it) in having to do additional request to get the thumbnail of the post because it do not belong to the DB structure of the post, but to the one of the attachment.

Your question hints into extending the problems even further, not only the users will know what post type you use but also what meta data you have and in what format it is.

What you should do is to write your own end point and your own API that accepts only what it needs and return what the user actually needs.

And btw, never let anyone query all your posts, this is just an invitation to an easy DOS attack against the site.

Answered by Mark Kaplun on January 2, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP