简体   繁体   中英

Create a custom Wordpress REST API endpoint with a action hook

I am trying to create a Wordpress action hook that fires when a post is published, updated or deleted.

When the action hook is triggered the new endpoint in the REST API should be created where I would store the time of the event, and some other basic info.

So far I managed to only create a REST endpoint but I don't know how to create it or update it inside the action hook function.

I am a beginner in PHP and would really appreciate if someone posted an example on how to this because I could not find any.

This is the code I tried so far, it is wrong and I cannot find an example to try it base on that. I managed to create the REST route but cannot update it with the action hook function.

<?php

function update_all($data) {
  $response = new WP_REST_Response('TEST');
  return $response;
}

add_action('save_post', 'send_update', 10, 3);

 function send_update(){
   $response = new WP_REST_Response('UPDATE');
   return $response;
}

function start_update(){
  $datum = date("dmY");
  register_rest_route('update/', $datum, array(
    'methods' => 'GET',
    'callback' => 'update_all'
  )); 
}


add_action('rest_api_init', 'start_update');
?>

Thanks!

So it seems that this was a wrong approach and it wasn't possible to do it with REST Endpoint. I tried a different approach where I just saved a new JSON file in functions.php and this worked as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM