1

I've used WordPress for a few years now and I'm wanting to set up a WordPress instance and use it for API calls. I've never used the RESTapi capabilities of WordPress before. I've done some tutorials and can call pages and post. Instead of calling a page or a post I just want to do a POST request to a file instead that will then run some logic.

My projects goal is going to have videos using iframes running on other peoples webpage and when a user hits play on that video it will do an AJAX call to the API and post some details like the video id, name, website it was watched on ect. I want the logic to then email a customer who filmed that video.

I will use the backend to create a DB of users relevant to the video Ids.

Is this the correct use for the RESTapi and can I call just a file instead of posts and pages or should I be doing this another way? I'm not wanting a front-end for this instance. Just CMS and api calls.

1
  • It makes less sense to think of it as calling/running a file, and more sense to think of it as running code. The code you want to run doesn't have to be in its own file. It sounds like what you're asking is how to create a custom endpoint to execute your own code
    – Tom J Nowell
    Nov 20 '20 at 14:01
3

Make custom API endpoint and move the logic from your PHP file into there instead

For example, the code below will create an endpoint in /wp-json/my/v1/video/<id>

add_action( 'rest_api_init', function() {
  register_rest_route( 'my/v1', '/video/(?P<id>\d+)', [
    'methods'             => 'GET',
    'callback'            => 'get_video_data',
    'permission_callback' => '__return_true',
  ] );
} );

function get_video_data( $params ) {
  $video_id = $params['id'];

  // do something like calling the DB where your video data is stored
  // you can use custom post type to store the data
  
  return $video_id;
}
4
  • 1
    I've edited the code to include a permission_callback parameter. Without this WP 5.5+ will issue a deprecation warning. I've given it the function __return_true so that it's accessible to everybody
    – Tom J Nowell
    Nov 20 '20 at 14:05
  • Nice, didn't know about that, thanks
    – hrsetyono
    Nov 20 '20 at 14:06
  • @hrsetyono brilliant thank you! I read you could look at custom posts but did not see anything on custom endpoints. Another noob question where would a store the new file? is they a wp-json folder? Nov 20 '20 at 14:28
  • @monkeyman905 in a plugin or theme functions.php, you would never make changes outside of plugins or themes. wp-json is not a physical folder on the system, all requests are handled by WordPress' main index.php via rewrite rules and routed to the appropriate functions as specified by the APIs
    – Tom J Nowell
    Nov 20 '20 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.