1

I registered a custom post type called wasb_message with show_in_rest set to true and rest_base set to 'messages' so the resource is reachable at endpoint https://mydomain/wp-json/wp/v2/messages (using the WP_REST_Posts_Controller class). The custom post type has a custom meta field called wasb_status with an integer value, how can I add a custom parameter so when I do a get request to endpoint https://mydomain/wp-json/wp/v2/messages?status=2 I retrieve messages with wasb_status equal to 2 without register a new route?

I read this code reference page and this old question but I can't get it working, using Postman to send get request I get:

{
    "code": "rest_invalid_param",
    "message": "Parametro(i) non valido(i): status",
    "data": {
        "status": 400,
        "params": {
            "status": "Stato non consentito."
        },
        "details": {
            "status": {
                "code": "rest_forbidden_status",
                "message": "Stato non consentito.",
                "data": {
                    "status": 401
                }
            }
        }
    }
}

2 Answers 2

1

I solved following this answer and writing:

public function query_wasb_messages_by_status( $args, $request ) {

        if ( ! is_null( $request->get_param( 'message_status' ) ) ) {
            $args['meta_query'] = array(
                '_wasb_message_status' => array(
                    'key'     => '_wasb_message_status',
                    'value'   => (int) $request->get_param( 'message_status' ),
                    'compare' => '=',
                    'type'    => 'numeric'
                )
            );
        }

        return $args;

    }
add_filter( 'rest_wasb_message_query', array( $this, 'query_wasb_messages_by_status'), 10, 2 );

My problem is I used status as parameter name but status already exists for posts ('draft', 'published', etc...) so I changed the name to message_status...

0

As per the reply by Haris it should be something like this:

function wasb_rest_parameter($args, $request) {
    if( isset($request["wasb_status"]) && is_numeric($request["wasb_status"]) ) {
        $args['meta_key'] = 'wasb_status';
        $args['meta_value'] = intval($request["wasb_status"]);
    }       
 
    return $args;
}
add_filter('rest_wasb_message_query', 'wasb_rest_parameter', 10, 2);

Not yet tested. If it does not work, will update the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.