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 front, that would be great!

1
1

If you are developing a theme, the proper place to put your code in this case if your theme’s functions.php file. This is the file that is surely going to be run when your website is being accessed.

If you are developing a plugin, you can put your code inside a php file (like foo.php) and then include/require it in your template, whichever suits your needs.

Don’t save or alter ANY file outside the wp-content folder, or your plugins. These are going to be overridden by WordPress updates, and have a chance to be identified as malware by some anti-malware plugins/server apps.

You can actually put your code directly inside your plugin’s core file, but i prefer to categorize the functions in case i need to access or modify them quickly later (personal opinion).

Leave a Reply

Your email address will not be published. Required fields are marked *