I am new to the WP REST API, and I am trying to fetch a single post of a CPT from a list of posts. With the below code (that I have kept abbreviated), I can return JSON data of 10 posts displayed on the screen from which I can return chosen fields. But do I return only the one post when it's selected, i.e., the 'postTitle' element? Many thanks in advance.
function displaySingleRole() {
let postData = document.getElementById( 'postTitle' );
if (postData) {
fetch( '/wp-json/wp/v2/my_posts/' )
.then( function( response ) {
return response.json();
})
.then( function( data ) {
console.log( data );
})
.catch( function( error ) {
console.log( error );
});
}}
I am new to the WP REST API, and I am trying to fetch a single post of a CPT from a list of posts. With the below code (that I have kept abbreviated), I can return JSON data of 10 posts displayed on the screen from which I can return chosen fields. But do I return only the one post when it's selected, i.e., the 'postTitle' element? Many thanks in advance.
function displaySingleRole() {
let postData = document.getElementById( 'postTitle' );
if (postData) {
fetch( '/wp-json/wp/v2/my_posts/' )
.then( function( response ) {
return response.json();
})
.then( function( data ) {
console.log( data );
})
.catch( function( error ) {
console.log( error );
});
}}
Share
Improve this question
asked Mar 10 at 6:40
MichaelMichael
312 bronze badges
1
|
1 Answer
Reset to default 0To help you, we need to know what the "my_post" action looks like in your code. Somewhere in your code, there must be an add_route
with "my_post." Can you show us what it looks like?
add_route('my_post', array(
...
));
By default, you can filter your posts in WordPress using the following route: ?rest_route=/wp/v2/posts/${POST_ID}
.
wp/v2/my_posts/5
e.g. – mmm Commented Mar 10 at 7:55