JetLagFox
JetLagFox

Reputation: 250

Get slug on WordPress custom endpoint

I have created a WordPress custom endpoint with the following code:

function wl_page_by_slug( $slug ) {

  var_dump($slug);

  return $slug['slug'];
}

add_action('rest_api_init', function() {
  register_rest_route('wl/v1', 'post/(?P<slug>[a-zA-Z0-9-]+)', [
    'methods' => 'GET',
    'callback' => 'wl_page_by_slug',
  ]);
});

But can't access to the data inside $slug as it is protected. How can I get it?

Upvotes: 2

Views: 945

Answers (1)

Kelvin Mariano
Kelvin Mariano

Reputation: 1021

Use the code below and see if it works for you:

function wl_page_by_slug( $slug ) {

  echo "<pre>";
  print_r($slug['slug']);
  echo "</pre>";

  //remember if here should always return in json
  return array( $slug['slug'] );
}

add_action('rest_api_init', function() {
  register_rest_route('wl/v1', 'post/(?P<slug>[a-zA-Z0-9-]+)', [
    'methods' => 'GET',
    'callback' => 'wl_page_by_slug',
  ]);
});

For more information https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

Upvotes: 3

Related Questions