0
votes

I am working on writing my own custom endpoint with the WordPress REST API. I currently have a registered endpoint for a single post using the post's ID.

$version = '1';
$namespace = 'vendor/v' . $version;
$base = 'route';
register_rest_route( $namespace, '/' . $base . /(?P<id>[\d]+)', array(
  array(
  'methods'  => WP_REST_Server::READABLE,
  'callback' => 'get_data_function',
  ),

So when I add (?P<id>[\d]+) to the end of the registered rest route that would grab only data for the post with the specific ID. Is this possible to do with the post's slug instead? So the route would be registered the same, but instead of adding (?P<id>[\d]+) I would add something similar that would register it for the post's slug

I was doing some research into this, but couldn't find any information on it

1
@Dhruv I've seen/used that method before using the slug parameter, but I wasn't sure if it was possible to do it the same way I presented above with the ID example, instead of using the slug parameter option. - user9664977

1 Answers

1
votes

I found the answer to my own question. If anyone stumbles upon this and is looking for an answer I used (?P<slug>[a-zA-Z0-9-]+) which checks the slug in the REST Endpoint. So as an example:

register_rest_route('test/v1', 'posts/(?P<slug>[a-zA-Z0-9-]+)', [
    'methods' => 'GET',
    'callback' => 'post_single',
]);


function post_single($slug) {

    $args = [
        'name' => $slug['slug'],
        'post_type' => 'post'
    ];

    $post = get_posts($args);

        $data['id'] = $post[0]->ID;
        $data['title'] = $post[0]->post_title;
        $data['slug'] = $post[0]->post_name;
        $i++;

    return $data;

}

If you were then to go to https://your-website.com/wp-json/test/v1/posts/hello-world

it would grab data for the post with the slug of hello-world