1

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!

Marija
  • 31
  • 1
  • 7
  • Hi, and welcome to Stack Overflow! You can read about [wordpress hooks](https://developer.wordpress.org/plugins/hooks/custom-hooks/) at that link. The function you are probably looking for is `do_action()` –  Feb 26 '19 at 20:24
  • Thank you for your reply! I tried adding add_action hook -> add_action( 'save_post', 'send_update', 10, 3 ); but cannot find a way to register a rest route inside the function send_update – Marija Feb 26 '19 at 20:28
  • Could you post the relevant code you are trying? –  Feb 26 '19 at 20:29
  • I will update my question with the code I tried so far – Marija Feb 26 '19 at 20:56
  • Hmm. Looks okay. Of course, I've never worked with REST API specifically. I probably can't help you further, other than ask you to clarify what you are trying to achieve . What exactly is broken? –  Feb 26 '19 at 23:31
  • I am trying to update a REST route within the add_action function send_update. I successfully created the route but when I try to update it, nothing happens – Marija Feb 27 '19 at 08:01

1 Answers1

1

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.

Marija
  • 31
  • 1
  • 7