WordPress documentation, bloggers, and StackExchange answerers have done a great job of describing the code you write to make a custom REST endpoint, but I cannot find any documentation that describes exactly WHERE you place the code.

Say I have an endpoint that I want to return the string “foo”. From my reading, I implement a function like this:

function my_foo() {
    return "foo";
}

and I register the function with a call like this:

add_action( 'rest_api_init', function () {
    register_rest_route( 'mycompany/v1', '/foo/', array(
            'methods' => 'GET',
            'callback' => 'my_foo'
    ) );
} )

There is nothing difficult about this, but for the life of me I cannot figure out WHERE to put these.

For the REST endpoint, I assume I would put the function inside a file at:

wp-json/mycompany/v1/foo.php

but it would be nice to know for sure.

As for the add_action() call I am also having a bear of a time finding out where the call goes.

The documentation here fails to describe where these calls should live, as does the article here (and many other sources I have found).

If anybody could point out where these locations are documented, or that I’m missing something right in fron, that would be great!

Thanks!

Read more here: When adding a custom REST endpoint, where do you put the endpoint function, and where do you put the function registration call?


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: