0

we are using wordpress as a headless cms, using custom post type and advanced custom field plugin, we are entering data in the fields in custom posts, localhost:8888/wordpress/wp-json/wp/v2/places?city=xyz this is working fine but we need to use filters in this url so that we can fetch data as per the required filter(field specific from custom post).

8
  • If I've understood correctly, you want to do some kind of action, or manipulate input, when a field is updated via POST. Is this correct? – Ted Stresen-Reuter Sep 6 '19 at 12:33
  • No, I only want filter param to use in api to get the specific data. – Anuj Agnihotry Sep 6 '19 at 13:05
  • Can you please provide an example? For example, given a CPT with an "age" field, etc. I'm not understanding what you need as is. Thanks. – Ted Stresen-Reuter Sep 6 '19 at 13:10
  • see when I use the api url, I get all the posts data, if there is 100 custom posts under "places" then a collection of all 100 posts returns in json, but I want to have filter in api/url, so that only selected data comes in, – Anuj Agnihotry Sep 6 '19 at 13:30
  • Ok, can you please update your question with an example of the criteria you want to use? Are you trying to filter on an ACF field, a tag, a category, an author?? – Ted Stresen-Reuter Sep 6 '19 at 13:32
0

ACF adds post meta, so, you will need to modify the query using the pre_get_posts action. Specifically, you'll need to get the city name from the $_GET params and modify the query adding something like the examples in the pre_get_posts documentation. Essentially, something like this:

add_action( 'pre_get_posts', function(&$query) {
    if( is_main_query() && '' != $_GET['city'] ) {
        $query->set( 'meta_query', [
            [
                'key'     => 'city',
                'value'   => $_GET['city'],
                'compare' => '='
            ]
        ]);
    }
});

Note that you should also sanitize the input prior to adding it to the meta_query.

It is imperative that you read the documentation and understand it fully. There are plenty of small things that can throw you off, like the fact that the $query variable is passed in by reference (not returned by the function) so any changes you make are indeed affecting the main query in realtime (you don't return anything in an action, only in filters).

If you are unable to get this to work, you might also consider using the posts_clauses filter but I'm not sure if that's what you are looking for.

Sorry for the delay in responding. I had to do a fair amount of research and testing to make sure this answer would work.

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.