自定义API Wordpress端点失败

时间:2018-04-04 17:00:53

标签: wordpress wordpress-rest-api

{“code”:“rest_no_route”,“message”:“找不到与网址和请求方法匹配的路由”,“数据”:{“状态”:404}}

我试图确定我的代码有什么问题。我为wordpress编写了一个自定义api端点,但是在尝试访问url时遇到了上述错误。我的代码如下:

 $this->loader->add_action('rest_api_init', $plugin_public, 'create_api_webhook');

 public function create_api_webhook() {
    register_rest_route('learn2/v1', '/api/', array(
        'methods' => 'GET',
        'callback' => array($this, 'learn2_api_webhook')
    ));
}

public function learn2_api_webhook() {
    global $wpdb;
    $args = array('post_type' => 'sfwd-courses',
        'post_status' => 'publish',
        'order' => 'DESC',
        'orderby' => 'ID',
    );
    $loop = new WP_Query($args);
    $courses = array();
    $lessons = array();
    while ($loop->have_posts()) : $loop->the_post();

        $mylessons = learndash_get_lesson_list($post->ID);
        $lessons = array();
        foreach ($mylessons as $lesson) {
            $topics = array();
            $mytopics = learndash_get_topic_list($lesson->ID, $post->ID);
            foreach ($mytopics as $topic) {
                $topics[] = array('id' => $topic->ID, 'title' => $topic->post_title);
            }
            $lessons[] = array('id' => $lesson->ID, 'title' => $lesson->post_title, 'topics' => $topics);
        }
        $courses[] = array('id' => $post->ID, 'title' => $post->post_title, 'lessons' => $lessons);


    endwhile;


    return json_encode($courses);
}

我试图访问网址:

http://localhost/community_staging/wp-json/learn2/v1/api/ but I get the above error.

我正在运行最新的wordpress

1 个答案:

答案 0 :(得分:0)

$this->loader->add_action('rest_api_init', $plugin_public, 'create_api_webhook');

$ plugin_public没有指向正确的班级。