Create the JSON endpoint that accepts a WP_Post
ID.
add_action( 'rest_api_init', function() {
register_rest_route( 'api/v2', '/post/(?<id>\d+)', array (
'methods' => 'GET',
'callback' => 'get_post_content',
) );
} );
Handle the endpoint to return a post’s content based on the ID passed.
function get_post_content( WP_REST_Request $request ) {
$post = get_post( absint( $request->get_param( 'id' ) ) );
if ( ! $post ) {
return 'Invalid ID';
}
return apply_filters( 'the_content', $post->post_content );
}
Get the data with jQuery.
<script>
jQuery.get( "/wp-json/api/v2/post/504", function( data ) {
jQuery( ".result" ).html( data );
});
</script>
(Optional) – Localize the REST URL .
wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ) ) );
<script>
jQuery.get( wpApiSettings.root + "api/v2/post/504", function( data ) {
jQuery( ".result" ).html( data );
});
</script>