I'm building a theme from scratch that will use vue.js under the hood. I'm now using the standard wordpress endpoint to fetch pages and posts, I would really create my custom endpoint to pass as a response, a custom set of data instead of the default one provided by the REST API.
I've already registered a custom endpoint for the menu and it's working fine. I want now to register two more endpoints to get pages and posts, but I'm not able to make the things work. I will get a 404 or a 500 error from the endpoint and I need to fix this. To get evary page or post I'm using the slug, this mean that the GET
or POST
requests needs to have that parameters as querystring. I don't know if my code is correct, but I'm not able to get it inside my functions.php
file. Any help will be appreciated.
functions.php
// NB: the code is part of a small class that manage the routes. the register_rest_route function
// is inside a class method and the rest_api_init is called correctly
register_rest_route( 'theme/v1', '/pages/', array(
'method' => 'GET',
'callback' => array($this, 'get_page_data')
));
public function get_page_data( $request )
{
//var_dump( $request );
$slug = $request->get_params('slug');
$page = get_page_by_path( $slug, OBJECT, 'page' );
$page_meta = get_page_meta( $page->ID );
$images = get_post_gallery_images( $page->ID );
foreach( $images as $image_url ){
$attachments_url[] = $image_url;
}
$data = array(
'ID' => $page->ID,
'title' => get_the_title( $page->ID ),
'content' => strip_shortcodes($page->post_content),
'excerpt' => $page->post_excerpt,
'page_meta' => $page_meta,
'attached_images' => $attachments_url,
'featured_image' => get_the_post_thumbnail_url( $page->ID )
);
return $data;
}
// In the vue app js file the url for the request is
https://mysitedomain.com/wp-json/theme/v1/pages?slug=pageslug