Wp Rest Api Custom End point
Asked Answered
O

2

5

Im trying to add a custom end point to my wp-rest api the latest version. I have this already but the one with the slug param at the end does not work.. Does any one know why.. would be great if anyone could help..

     register_rest_route( 'wp/v2', '/guestmix', array(
        array(
            'methods'         => WP_REST_Server::READABLE,
            'callback'        => array( $this, 'get_guestmixes' )
        ),
        'schema' => array( $this, 'get_public_item_schema' )
    ) );

    register_rest_route( 'wp/v2', '/guestmix/(?P<slug>\d+)', array(
        'methods' => 'GET',
        'callback' => 'get_guestmix'
    ) );
Ossification answered 26/1, 2016 at 21:35 Comment(0)
A
8

i guess it because you used d metacharacter for regex (?P<slug>\d+) that's mean for digit, please try use S instead. The code should look like this

register_rest_route( 'wp/v2', '/guestmix/(?P<slug>\S+)', array(
    'methods' => 'GET',
    'callback' => 'get_guestmix'
) );

this is cheat sheet for reference http://www.phpliveregex.com/

Alpestrine answered 4/2, 2016 at 9:56 Comment(2)
I have been looking for cheat sheet for WP rest routes for some time now and by chance came across this page (it may be because I used edge to sear h instead of chrome) but finally I have chance at finding the solution to my url regex, I hate regex enough (despite the 'wow thats impressive' thoughts I get now and then) my problem was that my url needed to be url encoded and had 19 sections - yes I know...Gastropod
If only Wordpress documentation cared to explain which metacharacters we can use.Parrnell
G
2

The above answer works for me, though I implemented the regular expression slightly differently, following a 2019 gist, that covers different url/slug-structure scenarios.

register_rest_route( 'wp/v2', '/guestmix/(?P<slug>[a-zA-Z0-9-]+)', array(
    'methods' => 'GET',
    'callback' => 'get_guestmix'
) );

Hope this helps

Gumbo answered 24/8, 2019 at 4:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.