Skip to content

Instantly share code, notes, and snippets.

@panayotoff
Created October 22, 2018 11:08
Show Gist options
  • Save panayotoff/a2df55383d71da133d45478ac84699bd to your computer and use it in GitHub Desktop.
Save panayotoff/a2df55383d71da133d45478ac84699bd to your computer and use it in GitHub Desktop.
Simple rest controller to get page by slug
<?php
/**
* @package Any_Rest
* @version 1.7
*/
/*
Plugin Name: Any Rest
Description: Get any page by slug
Usage: http://test1.localhost/wp-json/anyrest/v2/apt?slug=hello-world
*/
add_action('rest_api_init', 'any_post_api_route');
function any_post_api_route()
{
register_rest_route('anyrest/v2', '/apt/', [
'methods' => 'GET',
'callback' => 'get_content_by_slug',
'args' =>[
'slug' => ['required' => false]
]
]);
}
/**
*
* Get content by slug
*
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
function get_content_by_slug(WP_REST_Request $request)
{
// get slug from request
$slug = $request['slug'];
// get title by slug
$return = get_page_by_path($slug, ARRAY_A, array('page', 'post'));
if ( $return['post_content'] ) {
$response = new WP_REST_Response( $return );
} else {
$response = new WP_Error( 'post_empty', 'Post is empty', array( 'status' => 404 ) );
}
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment