admin管理员组

文章数量:1122846

I have a custom post type called "crowdfunding" which contains two Advanced Custom Fields called campaign_start_date and campaign_end_date (in addition to several others). I'd like to create an API URL that will:

  • Only retrieve posts where now is between campaign_start_date and campaign_end_date
  • Order posts by campaign_start_date asc

I've worked out how to return the ACF fields I need, but I can't seem to get the filtering and ordering worked out. The following query params

/wp-json/wp/v2/crowdfunding?per_page=6&
_fields%5B%5D=title&
_fields%5B%5D=link&
_fields%5B%5D=date&
_fields%5B%5D=excerpt&
_fields%5B%5D=acf&
_fields%5B%5D=_links

Will return posts with the following info (note the start/end fields).

But I can't get the filtering and ordering working. I'm researching how to add a filter to my functions.php, but I don't want to mess up other API calls that I'm making for this same feature. What are my options?

My site is running WordPress 6.4.4.

I have a custom post type called "crowdfunding" which contains two Advanced Custom Fields called campaign_start_date and campaign_end_date (in addition to several others). I'd like to create an API URL that will:

  • Only retrieve posts where now is between campaign_start_date and campaign_end_date
  • Order posts by campaign_start_date asc

I've worked out how to return the ACF fields I need, but I can't seem to get the filtering and ordering worked out. The following query params

/wp-json/wp/v2/crowdfunding?per_page=6&
_fields%5B%5D=title&
_fields%5B%5D=link&
_fields%5B%5D=date&
_fields%5B%5D=excerpt&
_fields%5B%5D=acf&
_fields%5B%5D=_links

Will return posts with the following info (note the start/end fields).

But I can't get the filtering and ordering working. I'm researching how to add a filter to my functions.php, but I don't want to mess up other API calls that I'm making for this same feature. What are my options?

My site is running WordPress 6.4.4.

Share Improve this question edited May 5, 2024 at 22:02 commadelimited asked May 5, 2024 at 21:56 commadelimitedcommadelimited 258 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You could consider using the rest_{$this->post_type}_query filter hook to modify the result of certain REST API queries.

To not mess with existing API calls, you could look at using new query parameters that have not been used. Then, use these parameters in your filter. For example:

GET /wp-json/wp/v2/crowdfunding?per_page=6&foo_parameter=bar
function my_plugin_filter( $args, $request ) {
  if ( $request->get_param( 'foo_parameter' ) ) {
    // Modify $args as needed here.
  }

  return $args;
}
add_filter( 'rest_crowdfunding_query', 'my_plugin_filter', 10, 2 );

本文标签: rest apiWordPress API V2filter and order by ACF field