How To Retrieve Any Post Type For WordPress V2 REST API (Create A Custom Endpoint)

WordPress Tutorials by Allure Web Solutions

In this post, I show how to create a custom API endpoint for the WordPress REST API V2. With this custom endpoint, you’ll be able to retrieve any post/page regardless of post type by using the slug.

This is useful because in V2 of the WordPress REST API there is no way to query all posts/pages. You have to specify either the post or page endpoint.

The PHP

add_action('rest_api_init', 'any_post_api_route');
public function any_post_api_route()
{
    register_rest_route('plugin-name/v2', '/any-post-type/', array(
        'methods' => 'GET',
        'callback' => 'get_content_by_slug',
        'args' => array(
            'slug' => array(
                'required' => false
            )
        )
    ));

}

/**
 *
 * Get content by slug
 *
 * @param WP_REST_Request $request
 * @return WP_REST_Response
 */
public 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'));

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

}

The AJAX

$.ajax({
    url: '/wp-json/plugin-name/v2/any-post-type?slug=' + postUrl,
    success: function (data) {
        var page = data;
        modalContent.html(page.post_content);
    },
    cache: false
});

Visual Composer

If you are using Visual Composer, you’ll notice that the API route that we created doesn’t render the Visual Composer shortcodes. For that we’ll need to add an extra filter for the content. The code would look like this:

public function get_content_by_slug( WP_REST_Request $request ) {
	WPBMap::addAllMappedShortcodes();

	// get slug from request
	$slug = $request['slug'];

	// get title by slug
	$return = get_page_by_path( $slug, ARRAY_A, array( 'page', 'post' ) );

	// render shortcodes from Visual Composer
	$return['post_content'] = apply_filters( 'the_content', $return['post_content'] );

	$response = new WP_REST_Response( $return );

	return $response;

}

If you have any questions, including how to modify this for the WordPress Plugin Boilerplate, please don’t hesitate to ask in the comments!

Credits: https://www.coditty.com/code/wordpress-rest-api-how-to-get-content-by-slug