0

Iam using the "ACF" plugin with "ACF to REST API". I found a solution for querying a custom field over REST API.

I inserted this into my functions.php:

add_filter( 'rest_{type}_query', function( $args ) {
    $args['meta_query'] = array(
        array(
            'key'   => 'my_field',
            'value' => esc_sql( $_GET['field'] ),
        )
    );

    return $args;
} );

Url: /wp-json/wp/v2/posts?field=test The wildcard {type} can be: post | user | comment | attachment | custom post type | taxonomy

This solution is not perfect. Once this code snipped is added, the filter works but if you go to /v2/{type} <-- which usually lists all, this stops working.

Any solution for that?

1
  • you should not be using esc_sql like that, esc_sql is only to be used in very specific circumstances, most people coding with WP will never need to use it. Otherwise is there a reason you're modifying all API queries, not just the ones that have field set? Why not use the existing parameters for meta queries instead of adding a new one?
    – Tom J Nowell
    Commented Nov 8, 2022 at 17:38

1 Answer 1

0

I got that working :)

add_filter('rest_myRoute_query', function($args, $request) {
  $fields = array('myCustomField');

  foreach ($fields as $field) {
    if (! empty($request[$field])) {
      $args['meta_query'][] = array(
        'key'   => $field,
        'value' => esc_sql($request[$field]),
      );
    }
  }

  return $args;
}, 10, 2);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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