airesvsg / acf-to-rest-api

Exposes Advanced Custom Fields Endpoints in the WordPress REST API
https://wordpress.org/plugins/acf-to-rest-api/
1.33k stars 111 forks source link

Orderby ACF not working #382

Open Elwazeery opened 3 years ago

Elwazeery commented 3 years ago

Hello I tried to order the posts by acf but I see it's not working https://mysite.win/wp-json/wp/v2/cars?filter[orderby]=star&filter[order]=desc I don't know what is wrong here

leok85 commented 2 years ago

I'll answer here that maybe I can help other people.

For example I have a post type called events and I want to sort by date field.

add_filter( 'rest_events_query', function( $args ) {
  if ($args['orderby'] === 'date') {
      $args['meta_key'] = 'date';
      $args['meta_type'] = 'DATETIME';
  }

  return $args;
});

API URL: .../acf/v3/events?orderby=date&order=asc

I also have this other function that I don't know if it's really necessary. In some places in my application I need to order by "menu_order" (Post Types Order plugin) and in other places by date

add_filter( 'rest_events_collection_params', 'filter_add_rest_orderby_params', 10, 1 );

function filter_add_rest_orderby_params( $params ) {
  $params['orderby']['enum'][] = 'menu_order';
  $params['orderby']['enum'][] = 'meta_value';
  return $params;
}