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')); 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; }
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); }, error: function () { // default to legacy method on error modalContent.load(postLink + ' #modal-ready'); }, 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:
function get_content_by_slug( WP_REST_Request $request ) { // Visual Composer shortcodes include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); if ( is_plugin_active( 'js_composer/js_composer.php' ) ) { WPBMap::addAllMappedShortcodes(); } // get slug from request $slug = $request['slug']; // get title by slug $return = get_page_by_path( $slug, ARRAY_A, get_post_types() ); // if post content is not empty if ( $return['post_content'] ) { $return['post_content'] = apply_filters( 'the_content', $return['post_content'] ); $response = new WP_REST_Response( $return ); } // if empty, return error else { $response = new WP_Error( 'post_empty', 'Post is empty', array( 'status' => 404 ) ); } 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