Wordpress Endpoint for TextBlocks plugin
<?php
/**
* Grab text block by shortcode
*
* @param array $shortcode Shortcode for the required textblock
* @return WP_REST_Response|WP_Error Text block in response object or error if not found
*/
function ifour_get_text_block( $request ) {
$items = new WP_Query([
'post_type' => 'text-blocks',
'name' => $request['field'],
'posts_per_page' => 1,
'post_status' => 'publish'
]);
if (! $items->have_posts() ) {
return new WP_Error( 'no_text_block_found', 'Invalid text-block request', array( 'status' => 404 ) );
}
// Build up the response object
$response = new WP_REST_Response($items->get_posts());
// // Add a custom status code
$response->set_status(200);
// Add some headers
$response->header('X-WP-Total', $items->found_posts );
$response->header('X-WP-TotalPages', $items->max_num_pages);
return $response;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'ifour/v1', '/text-blocks/(?P<field>[\\w\\-\\_]+)', array(
'methods' => 'GET',
'callback' => 'ifour_get_text_block',
));
});