最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Fetch a single post from a list of posts using the REST API

programmeradmin7浏览0评论

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
  • 3 to get a unique "my_post", you can request it by it's id on the endpoint wp/v2/my_posts/5 e.g. – mmm Commented Mar 10 at 7:55
Add a comment  | 

1 Answer 1

Reset to default 0

To 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}.

发布评论

评论列表(0)

  1. 暂无评论