0

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). Screenshot of WordPress API response

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.

1 Answer 1

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 );
1
  • Oh, interesting. In this case I don't use the /crowdfunding for anything else. So I have no problem changing the result without a query param. I'll experiment, thank you. Commented May 8 at 3:24

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.