How to add a custom parameter to a WP API default route?

After a lot of digging I seem to have found a solution myself, and a pretty powerful one, which makes use of a rest_{ post_type }_query filter (replace the { post_type } part with the slug of your custom post type. You can use rest_post_query to alter the default /wp-json/wp/v2/posts request):

public function __construct() {  
    // Make sure you add those numbers at the end of the line, or it won't work
    add_filter( 'rest_opps_query', array( $this, 'get_opps_by_state' ), 10, 2 );  
}  
       
public function get_opps_by_state( $args, $request ) {

    $state = $request->get_param( 'state' );  

    if( $state == 'open' ) {
        $args[ 'meta_query' ] = array(
            'deadline' => array(
                'key' => 'deadline',
                'value' => date( 'Ymd' ), 
                'compare' => '>',
                'type' => 'DATE'
            )
        );
    } elseif ( $state == 'closed' ) {
        $args[ 'meta_query' ] = array(
            'deadline' => array(
                'key' => 'deadline',
                'value' => date( 'Ymd' ), 
                'compare' => '<',
                'type' => 'DATE'
            )
        );
    }

    return $args; 

}

So now I can use the default WordPress API route to fetch custom posts:

http://example.com/wp-json/wp/v2/opps

and filter its results based on my custom parameter, status:

http://example.com/wp-json/wp/v2/opps?status=open

http://example.com/wp-json/wp/v2/opps?status=closed

No custom routes needed!

Leave a Comment