问题描述
如何使用 WP REST API(v1 或 v2) 获取特定自定义帖子类型的所有帖子?我很新,试图理解如何做到这一点。
我目前正在使用 WP REST API v2,并通过这种方式获取所有帖子类型的列表
http://domain.com/wp-json/wp/v2/types
然后设法获取我感兴趣的帖子类型
http://domain.com/wp-json/wp/v2/types/the-icons-update
如何获取该特定内容类型的所有帖子?
我试过了
http://domain.com/wp-json/wp/v2/posts?filter[post_type]=the-icons-update
但它返回一个空数组 (我想它返回默认的帖子,在我的网站上只有我正在尝试检索的自定义帖子类型中的帖子) 。
可能会有一个问题,我如何注册的帖子类型?
function custom_post_type() {
$labels = array(
'name' => _x( 'The Icons Update', 'post type general name' ),
'singular_name' => _x( 'The Icons Update', 'post type singular name' ),
'add_new' => _x( 'Add Page', 'magazine' ),
'add_new_item' => __( 'Add New Page' ),
'edit_item' => __( 'Edit Page' ),
'new_item' => __( 'New Page' ),
'all_items' => __( 'All Pages' ),
'view_item' => __( 'View Page' ),
'search_items' => __( 'Search Pages' ),
'not_found' => __( 'No Page found' ),
'not_found_in_trash' => __( 'No Page found in the Trash' ),
'parent_item_colon' => '',
'menu_icon' => '',
'menu_name' => 'The Icons Update'
);
$args = array(
'labels' => $labels,
'description' => 'Holds our projects and project specific data',
'public' => true,
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields' ),
'has_archive' => true,
'taxonomies' => array('post_tag', 'category'),
'hierarchical' => false,
'query_var' => true,
'queryable' => true,
'searchable' => true,
'rewrite' => array( 'slug' => 'the-icons-update' )
);
register_post_type( 'magazine', $args );
flush_rewrite_rules();
}
add_action( 'init', 'custom_post_type' );
任何帮助这是非常感谢。
最佳解决方案
只需将下一个参数添加到功能 register_post_type 中,就可以在’menu_position’ 参数之前。 ‘show_in_rest’ => 真正
如果您使用插件注册您的 posttype,您可以使用下一个代码:
add_action( 'init', 'add_anuncios_to_json_api', 30 );
function add_anuncios_to_json_api(){
global $wp_post_types;
$wp_post_types['anuncio']->show_in_rest = true;
}
之后,您将能够从 mydomain.com/wp-json/wp/v2/posttype_slug 列出您的帖子
在我的情况下:mydomain.com/wp-json/wp/v2/anuncio
您还可以使用下一个代码注册新的基数:
add_action( 'init', 'add_anuncios_to_json_api', 30 );
function add_anuncios_to_json_api(){
global $wp_post_types;
$wp_post_types['anuncio']->show_in_rest = true;
$wp_post_types['anuncio']->rest_base = 'clasi';
$wp_post_types['anuncio']->rest_controller_class = 'WP_REST_Posts_Controller';
}
只需替换 anuncio
作为您的帖子类型的插件,’clasi’ 将成为您的路由。 mydomain.com/wp-json/wp/v2/clasi
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。