class Endpoint {
/**
* Construct
*/
public function __construct() {
add_action( 'rest_api_init', array( $this, 'rest_routes' ) );
}
/**
* Register rest routes
*/
public function rest_routes() {
// Route: wp-json/ventures/v1/products/<id>
register_rest_route(
'ventures/v1',
'/products/(?P<id>[\d]+)',
array(
'methods' => 'GET',
'callback' => array( $this, 'get_product' ),
'permission_callback' => '__return_true',
)
);
}
/**
* Callback function for getting product.
*
* @param object $request
*/
public function get_product( \WP_REST_Request $request ) {
$data = array();
// Arguments.
$args = array(
'post_type' => 'product',
'posts_per_page' => 1,
'p' => $request['id']
);
// Query.
$query = new \WP_Query( $args );
// Output.
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$data['id'] = get_the_ID();
$data['title'] = get_the_title();
}
}
wp_reset_postdata();
// REST response object.
$response = new \WP_REST_Response( $data );
// Return.
return $response;
}
}