WP REST API Custom endpoint don’t work in my plugin

Question

I would really appreciate help on this, as i have tried and tried.

I have made this very simple endpoint to som basic info from a custom post type called ‘ydelse’.

Here is my class for the creation of the custom rest endpoint

class jw_salonbooking_ydelseliste_REST_Controller extends WP_REST_Controller { 

    public function register_routes() {
        $version = '1';
        $namespace = 'jw_salonbooking/v' . $version;

        $base = '/ydelseliste/';
        register_rest_route( $namespace + $base, array(
            'methods' => 'GET',
            'callback' => array ($this, 'my_awesome_func'),
        ) );
    }


    public function register_hook() {
        add_action ( 'rest_api_init', array( $this, 'register_routes' )     );
    }

    public function my_awesome_func( $data ) {
        $posts = get_posts( array(
            'type' => 'ydelse',
        ) );

        if ( empty( $posts ) ) {
            return null;
        }

        $ydelseliste = array();
        $counter=0;

        foreach ($posts as $post) {
            $ydelseliste[$counter]['titel']       = $post->title;
            $ydelseliste[$counter]['pris']        = $post->jw_salon_booking_ydelse_pris;
            $ydelseliste[$counter]['varighed']    = $post->jw_salon_booking_varighed;
            $ydelseliste[$counter]['beskrivelse'] = $post->content;        
            $counter++;
        }

    return $ydelseliste;
    }
}

I then do this, in my constructor of my plugin.:

     require_once (dirname( __FILE__ ) . '/rest-routes/jw-salonbooking-ydelseliste-rest-controller.php');
     //* Registrer ydelseliste REST controller 
     $ydelseliste_route = new jw_salonbooking_ydelseliste_REST_Controller();
     $ydelseliste_route->register_hook();

I know my constructor is working because all the other add_actions are executing just fine. And while I was developing the route class I was getting errors from Postman when i was executing af GET request like this:

    https://zebrafinken.dk/testsite/wp-json/jw_salonbooking/v1/ydelseliste/

But now i am just getting this result:

{
    "code": "rest_no_route",
    "message": "Ingen rute blev fundet der matchede URL og anmodningen",
    "data": {
        "status": 404
    }
}

I hope there’s someone who will guide me in the right direction or have an answer to this.

0
, , Jacob Thygesen 4 years 2020-02-20T08:41:52-05:00 0 Answers 77 views 0

Leave an answer

Browse
Browse