Ronnie Zweers
Ronnie Zweers

Reputation: 121

Not able to pass parameter for post method wordpress REST service

I'm a newbie in Wordpress and the REST-API I have been able to get the GET function working but I'm not able to pass a parameter to the post function.
Below I have pasted my code. When entering http://localhost/wp-json/localhost/v1/activeitem the active id is resulted, but if I provide http://localhost/wp-json/localhost/v1/activeitem/123 I get {"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}.
When running /localhost/v1/activeitem?45 in REST API console in Wordpress I get "Done". So at this point I would like to know what am I doing wrong.
The idea of is that a xxx/activeitem call would give the active id and a xxx/activeitem[parameter] would do an update of the active item to the provided id.

function LocalHost_GetActiveItem() {
    global $wpdb;
    $querystr = "select option_value as pid from wp_options where option_name = 'acelive_active';";
    $activeitem = $wpdb->get_results($querystr);
    return $activeitem[0];
}

function LocalHost_SetActiveItem($id) {

    //return $id;
    return "done";
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'localhost/v1', '/activeitem/', array(
        array(
            'methods' => 'GET',
            'callback' => 'LocalHost_GetActiveItem',
        ),
        array(
            'methods' => 'POST',
            'callback' => 'LocalHost_SetActiveItem',
            'args' => array('id' => 234)
        ),
    ) );
} );

add_action( 'rest_api_init', function () {
    register_rest_route( 'localhost/v1', '/lastupdate/', array(
        'methods' => 'GET',
        'callback' => 'LocalHost_LastUpdate',
    ) );
} );

Upvotes: 1

Views: 2412

Answers (1)

HamzehXX
HamzehXX

Reputation: 187

Make sure your regex expressions are fine. for id you can use activeitem/(?P<id>[\d]+) in $route parameter of the register_rest_route() and if you want to update the id, make sure to set the $override parameter of the register_rest_route() to true

register_rest_route( 'localhost/v1', '/activeitem/(?P<id>[\d]+)', array(
          'methods' => 'POST',
        'callback' => 'LocalHost_SetActiveItem',
        'args' => array('id' => 234)

), true );

the reason why you get 404 error while providing xxx/activeitem/123 is that 123 is not captured and passed as an id on to your url, because the route is not provided the proper regex expression.

Upvotes: 1

Related Questions