Igor Simic
7 years ago

WordPress REST API - How to get content by slug


To get page content from WP API based on slug we can use this request:
/pages?filter[slug]=sample-page
same thing will be for posts
/posts?filter[slug]=hello-world
but how to get the content based just on slug and not defining the type of content (page, post...) same as 'native' wordpress is doing?

Well, for that we can use WP function get_page_by_path() which is used by WP core to serve the content requested when using SEO permalinks.
Best way to use it is to register new API route which will accept slug and send back content with comments.

So let'S register a route first, inside of functions.php file add this code:
add_action( 'rest_api_init', function () {

		  register_rest_route( 'my-theme/', 'get-by-slug', array(
		        'methods' => 'GET',
		        'callback' => 'my_theme_get_content_by_slug',
		        'args' => array(
		            'slug' => array (
		                'required' => false
		            )
		        )
		    ) );

		} );
and next let's create the callback function for pur URL:
 function my_theme_get_content_by_slug( WP_REST_Request $request ) {
    
    // get slug from request
    $slug = $request['slug']; 

    // get content by slug
    $return['content'] = get_page_by_path( $slug, ARRAY_A ); 
    
    // add comments to our content
    $return['content']['comments'] = get_comments( array( 'ID' => $return['content']['ID'] ) );
     

    $response = new WP_REST_Response( $return );
    return $response;

}


UPDATE 2017-10-24:
Maybe even better way is to use WP_Query:
$query = new WP_Query( array( 'post_type' => 'any','name'=>'slug' ) );