If you’re adding code that’s being hooked (with add_action()
, like in your example, or add_filter()
then it should go in your theme’s functions.php file.
But if it’s not your own personally developed theme then you run the risk of losing it if the theme updates. The better approach is to create a Child Theme, or better yet a simple plugin. Then you put your code in the child theme’s functions.php file or your own plugin file.
Regarding creating a webhook, if you need to have a URL that something can post JSON to, then a custom REST API endpoint would be the best way to go about it.
You can read the documentation on adding REST endpoints here, but here’s a brief overview.
The first thing is to register the route:
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/endpoint', array(
'methods' => 'POST',
'callback' => 'my_awesome_func',
) );
} );
This creates a URL at https://example.com/wp-json/myplugin/v1/endpoint
. This will be the webhook URL. The methods
argument means that it will accept POST requests, and callback
is the PHP function that will handle the request.
It just needs to be a callable function with a single argument that represents the request. This will also go in the functions file or plugin:
function my_awesome_func( $request ) {
// Do something here.
}
If the request is JSON in the body, then you can retrieve that using the get_json_params()
method of the request:
function my_awesome_func( $request ) {
$data = $request->get_json_params();
}
That will set $data
to a PHP array representing the JSON data. Then you can do with it what you’d like.
For testing, a simple method might be to log the request to the error log:
function my_awesome_func( $request ) {
$data = $request->get_json_params();
error_log( print_r( $data, true ) );
}
Where that ends up depends on your server setup, by try looking for an error_log
in the root directory, or debug.log
in wp-content/
.