我有一个自定义的帖子类型,叫做pronews
. 我在注册了show_in_rest
已启用。我正在使用WordPress 5.5。
然后我有了这个代码:
export const ProPost = wp.api.models.Post.extend( {
urlRoot: wpApiSettings.root + \'wp/v2/pronews\',
defaults: {
type: \'pronews\',
},
} );
export const ProPosts = wp.api.collections.Posts.extend( {
url: wpApiSettings.root + \'wp/v2/pronews\',
model: ProPost,
} );
const post = new ProPost( {id: 2454} );
console.log( post );
console.log( \'post urlRoot:\' + post.urlRoot );
console.log( \'post url:\' + post.url );
post.fetch().then( ( response ) => {
console.log( response )
}, ( why ) => {
console.log( why.responseJSON.code )
} );
// Double check that the endpoint is functionnal
fetch( wpApiSettings.root + \'wp/v2/pronews/2454\' )
.then( blob => blob.json() )
.then( ( response ) => {
console.log( response.id );
} );
在控制台中,我首先得到:
{…}
_changing: false
_pending: false
_previousAttributes: Object { type: "pronews", id: 2454 }
attributes: Object { type: "pronews", id: 2454 }
changed: Object { }
cid: "c3"
id: 2454
<prototype>: Object { urlRoot: "https://localhost/wp-json/wp/v2/pronews", defaults: {…}, constructor: i()
}
ProNews.js:17:9
post urlRoot:https://localhost/wp-json/wp/v2/pronews ProNews.js:18:9
post url:function(){var e=a.get("apiRoot")+a.get("versionString")+("me"===i?"users/me":i);return _.isUndefined(this.get("id"))||(e+="/"+this.get("id")),e} ProNews.js:19:9
但是主干API的请求是错误的
urlRoot
:
XHRGET https://localhost/wp-json/wp/v2/posts/2454 [HTTP/1.1 404 Not Found 340ms]
rest_post_invalid_id
对于调试,第二个HTTP请求的结果使用
window.fetch
, 显示自定义帖子类型的终结点存在并且可以正常工作:
XHRGET https://localhost/wp-json/wp/v2/pronews/2454 [HTTP/1.1 200 OK 587ms]
2454
最合适的回答,由SO网友:Sally CJ 整理而成
实际上,您不必扩展Post
模型(wp.api.models.Post
) 或Posts
集合(wp.api.collections.Posts
) 因为documentation 表示:
当您add REST API support to your custom post type
这意味着,您的自定义帖子类型将自动添加到wp.api.models
和wp.api.collections
列表,即。wp.api.models.<key>
和wp.api.collections.<key>
由此<key>
是柱状段塞in camel case。所以对你来说,关键是Pronews
— 或ProNews
如果职位类型为pro-news
.
因此,要访问模型/集合(或者简单地说,POST),您只需执行以下操作:
// Access one model (a single post). ID is required.
const post = new wp.api.models.Pronews( { id: 57 } );
// Access a collection (multiple models/posts).
const posts = new wp.api.collections.Pronews();
简单,嗯?:)(如果您愿意,您可以扩展您的帖子类型的模型/集合。
const ProPost = wp.api.models.Pronews.extend( ... )
)