Select posts using @wordpress/data with query based on custom field always returns all records

It appears that REST API doesn’t support all the meta_query parameters that WP_Query does. Only the basic meta queries with some comparison operators are supported.

Therefore we need to make one of workarounds to get what we want:

  • Add some REST API Filter to our theme/plugin
add_filter('rest_{post_type}_query', function($args, $request) {
    $params = $request->get_params();
    if(isset($params['meta_compare'])) {
        $args['meta_query'] = [[
            'key'     => $params['meta_key'],
            'value'   => $params['meta_value'],
            'compare' => $params['meta_compare'],
            'type'    => $params['meta_type'] ?? 'CHAR'
        ]];
    }
    return $args;
}, 10, 2);
  • Create some custom REST Endpoints
add_action('rest_api_init', function() {
  register_rest_route('myplugin/v1', '/posts-with-meta/', array(
    'methods' => 'GET',
    'callback' => 'my_custom_meta_query',
    'permission_callback' => function() { return true; }
  ));
});

function my_custom_meta_query($request) {
  $args = array(
    'post_type' => 'my_post_type',
    'meta_query' => array(
      array(
        'key' => 'my_data',
        'value' => array(50, 100),
        'compare' => 'BETWEEN',
        'type' => 'NUMERIC'
      )
    )
  );
  
  $query = new WP_Query($args);
  return rest_ensure_response($query->posts);
}

Then query it from our JavaScript:

const data = useSelect((select) => {
  return select(coreDataStore).getEntityRecords('root', 'myplugin/v1/posts-with-meta');
});