我在表wp_3_posts中有一些post_type为 "people "的帖子。这个post_type是使用管理列插件创建的。
我如何检索这些帖子?
Posts的文档提供了分类或标签的过滤功能,但post_type都不是。
https:/developer.wordpress.orgrest-apireferenceposts)。
谢谢你 :] 我在wp_3_posts表中有一些帖子,帖子类型为 "人"。
如果我对你的问题的理解是正确的,你想通过REST API获取自定义帖子类型的帖子。
你必须设置 show_in_rest
和 public
当你在wordpress中创建自定义文章类型时,在参数中加入""。
add_action( 'init', 'my_cpt' );
function my_cpt() {
$args = array(
'public' => true,
'show_in_rest' => true,
'label' => 'My Custom Post'
);
register_post_type( 'mycustompost', $args );
}
有了这些设置,你就可以在url中使用正确的参数来获取帖子类型的帖子。
所以,如果你只是想获取帖子,你可以使用。
https://yoursite.com/wp-json/wp/v2/mycustompost?per_page=10
我建议设置 per_page
来控制你是否有大量的帖子。
你也可以在不需要额外的HTTP请求的情况下使用 _embed
https://yoursite.com/wp-json/wp/v2/mycustompost?per_page=10&_embed=wp:term,wp:featuredmedia
例如,有了这个功能,你可以得到分类术语和不同大小的特色图片的URL。
因此,你不需要得到你网站的所有帖子(和帖子类型),然后按帖子类型过滤,而只需要得到这个帖子类型的帖子。你可以比使用全局参数进行更多的过滤。
https:/developer.wordpress.orgrest-apiusing-therest-apiglobal-parameters。
如果使用VueJS(在我看来性能更好),这看起来会像这样。
fetch("https://yoursite.com/wp-json/wp/v2/mycustompost?per_page=10")
.then(response => response.json())
.then((data => {
this.mycustompost = data;
}))
或者,如果使用标准的javascript,就会是这样的
let state = {
posts: [],
baseUrl: 'https://yoursite.com/wp-json/wp/v2/mycustompost',
perPage: '?per_page=10',
wpFetchHeaders: {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Expose-Headers': 'x-wp-total'
}
}
}