Wp Rest Api Custom End point

天大地大妈咪最大 提交于 2020-01-30 05:09:57

问题


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'
    ) );

回答1:


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/




回答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



来源:https://stackoverflow.com/questions/35024437/wp-rest-api-custom-end-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!