Search code examples
phprestactionadvanced-custom-fields

ACF fields empty for REST after post created


I'm sending push notifications every time a post it's published. All works as expected but ACF fields are empty. On contrary when I do re-save the post data comes through correctly.

Basic Workflow

  • User publish a post
  • Action is triggered to send push notification
  • Payload for ACF fields are empty (title, excerpt, rest off fields are ok)

I've been reading several threads, but could not achieve to deliver ACF fields to rest after creating the post.

What I have tried:

With priority 100 in order to make sure the post has already been save and then later get the info.

add_action(
      "save_post",
      ["YaguaretePluginApiBlog", "postPushNotification"],
      100,
      3
    );

Tried to use the transition_post_status, same results.

add_action(
       "transition_post_status",
       ["YaguaretePluginApiBlog", "postPushNotification"],
       99,
       3
     );

or

add_action('rest_after_insert_post', ["YaguaretePluginApiBlog", "postPushNotification"], 100, 3);

All of them triggers without problems but when it comes to get ACF fields nothing works.

also tried default acf/save_post, but unfortunately this one do not even fire up in contrast with the other actions

add_action("acf/save_post", [
      "YaguaretePluginApiBlog",
      "postPushNotification",
    ]);

This is what I have tried to get the acf fields

tried to use the_field function from ACF

$data[notificationType] = the_field(
       "yaguarete_push_notification",
       $_post->ID
     );

tried to use the post_meta to retrieve the field info

$data[notificationType] = get_post_meta($post["id"])[
       "yaguarete_push_notification"
     ][0]

tried to use the get_field from ACF

get_field("yaguarete_push_notification", $post["id"], false)

Nothing seems to work, could anyone with more experience point out what I'm doing wrong?

Thanks in advance


Solution

  • For anyone barging into same issue, I ended up using the following hook "rest_after_insert_post".

    After several tests which included only to trigger some actions only when post was published this did the trick:

    add_action(
          "rest_after_insert_post",
          ["YaguaretePluginApiBlog", "postPushNotification"],
          100,
          3
        );
    

    only send push when new post has been published

    function postPushNotification($post, $request, $creating)
      {
        $postOriginal = $post;
        $post = [get_post($post->ID)];
        $post = YaguaretePluginApiBlog::formatPosts($post)[0];
    
        //only send push notification when
        if (
          $postOriginal->post_type == "post" &&
          $postOriginal->post_status == "publish" &&
          $postOriginal->post_modified == $postOriginal->post_date
        ) {
    

    Hook already saved all meta data, including ACF fields which was my original issue not retrieving the values from this custom fields