首页 文章

在WordPress中为自定义帖子类型添加REST endpoints

提问于
浏览
0

我发现新的WordPress REST API(v2)的文档非常不充分和/或不完整 . 我有一个定义自定义帖子类型的插件,我想将REST API用于其预期目的 . 我试图按照文档中的示例进行操作,但是当我尝试相关的URL(http://example.com/wp-json/wp/v2/prsp/v1/attributes)时,我收到了"rest_no_route"响应 .

我的自定义帖子类型确实显示在“http://example.com/wp-json/wp/v2/types”的响应中 .

谁有人评论?

$args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true, 
    'show_in_menu' => 'prsp-top-level-handle',
    'rewrite' => array('slug' => 'prsp-attribute', 'with_front' => FALSE),
    'has_archive' => false,
    'hierarchical' => false,
    ...
    'show_in_rest' => true,
    'rest_controller_class' => 'WP_REST_Posts_Controller'
); 
register_post_type('prsp-attribute', $args);

...

$this->admin = new ProspectAdmin($this->get_version());

    $this->loader->add_action('admin_init', $this->admin, 'do_prsp_init', null, null);

    $this->loader->add_action('admin_menu', $this->admin, 'add_prsp_menus', null, null);

    $this->loader->add_action('rest_api_init', $this->admin, 'add_rest_api', null, null);

...

public function rest_get_attributes()
{
    return 'rest_get_attributes()'; // Temporary test for success
} // rest_get_attributes()

public function add_rest_api()
{
    register_rest_route('prsp/v1', '/attributes', array(
            'methods' => 'GET',
            'callback' => array($this, 'rest_get_attributes')
        ));
    register_rest_route('prsp/v1', '/attribute/(?P<id>\w+)', array(
            'methods' => 'GET',
            'callback' => array($this, 'rest_get_attribute')
        ));
} // add_rest_api()

而且,register_rest_route()的第二个参数的格式解释在哪里?

1 回答

  • 2

    该URL应为 http://example.com/wp-json/prsp/v1/attributes .

    您可以通过GET http://example.com/wp-json (或GET http://example.com/wp-json/prsp/v1 )列出现有路线和终点 .

相关问题