Wordpress publish_post hook not getting featured image and meta on first publish, but works on updating title

I've been struggling to find a solution for this and I don't know if it's the Gutenberg editor or if it's the hook publish_post .

Hook:

function api_method($post_id) {
    // If this is just a revision, don't send request
    if ( wp_is_post_revision( $post_id ) ) {
        return;
    }

    // Get Post Object
    $post = get_post($post_id);

    open_log($post);

    $postData = array(
        'unit' => get_post_meta($post_id, 'open_unit', true),
        'abstract' => get_post_meta($post_id, 'open_abstract', true),
        'image'   => get_the_post_thumbnail_url($post, 'full'),
        'title' => get_the_title($post),
        'url' => get_the_permalink($post),
    );

    open_log($postData);

    $auth = base64_encode(get_option('open_up_username') . ':' . get_option('open_up_api_key'));

    $status = get_post_meta($post_id, 'open_active', true) ? 'active':'paused';
    $openUnit = get_post_meta($post_id, 'open_unit', true);
//  $postMeta = get_post_meta($post_id);

//  open_log($postMeta);

    $responseApi = wp_remote_post(OPEN_REMOTE_POST, array(
            'headers' => array('Authorization' => 'Basic ' . $auth),
            'body' => 'unit='.$openUnit.'&status='.$status.'&abstract='.get_post_meta($post_id, 'open_abstract', true).'&image='.get_the_post_thumbnail_url($post_id, 'full').'&title='.get_the_title($post).'&url='.get_the_permalink($post)
        )
    );

    $response = new WP_REST_Response($responseApi, 200);

    $body = wp_remote_retrieve_body($responseApi);

    $responseBody = ( ! is_wp_error( $response ) ) ? json_decode( $body, true ) : null;

    $unit = isset($responseBody['unit']) ? $responseBody['unit'] : '';

    open_log($responseBody);
    open_log($unit);

    $update = update_post_meta($post_id, 'open_unit', $unit);

    open_log($update);
}

I'm using the post meta, featured image and title to post to a third party API. The API verifies the data and then returns a unit hash which I store in the post meta open_unit .

I'm also logging the data and responses in a log.txt file, and I'm getting this on initial publish:

object(WP_Post)#4421 (24) {
  ["ID"]=>
  int(240)
  ["post_author"]=>
  string(1) "3"
  ["post_date"]=>
  string(19) "2021-05-07 09:57:28"
  ["post_date_gmt"]=>
  string(19) "2021-05-07 07:57:28"
  ["post_content"]=>
  string(0) ""
  ["post_title"]=>
  string(11) "New post v3"
  ["post_excerpt"]=>
  string(0) ""
  ["post_status"]=>
  string(7) "publish"
  ["comment_status"]=>
  string(4) "open"
  ["ping_status"]=>
  string(4) "open"
  ["post_password"]=>
  string(0) ""
  ["post_name"]=>
  string(11) "new-post-v3"
  ["to_ping"]=>
  string(0) ""
  ["pinged"]=>
  string(0) ""
  ["post_modified"]=>
  string(19) "2021-05-07 09:57:28"
  ["post_modified_gmt"]=>
  string(19) "2021-05-07 07:57:28"
  ["post_content_filtered"]=>
  string(0) ""
  ["post_parent"]=>
  int(0)
  ["guid"]=>
  string(31) "https://grace.open-up.it/?p=240"
  ["menu_order"]=>
  int(0)
  ["post_type"]=>
  string(4) "post"
  ["post_mime_type"]=>
  string(0) ""
  ["comment_count"]=>
  string(1) "0"
  ["filter"]=>
  string(3) "raw"
}

array(5) {
  ["unit"]=>
  string(0) ""
  ["abstract"]=>
  string(0) ""
  ["image"]=>
  bool(false)
  ["title"]=>
  string(11) "New post v3"
  ["url"]=>
  string(45) "https://grace.open-up.it/recipes/new-post-v3/"
}

array(2) {
  ["success"]=>
  bool(false)
  ["message"]=>
  string(83) "Open Up - Si è verificato un problema con l'elaborazione dell'immagine in evidenza"
}

string(0) ""

int(1256)

The API is returning and saying that the image is invalid which is true because the image url is not showing in the $postData array.

After I edit the title and save, it logs below:

object(WP_Post)#4420 (24) {
  ["ID"]=>
  int(240)
  ["post_author"]=>
  string(1) "3"
  ["post_date"]=>
  string(19) "2021-05-07 09:57:28"
  ["post_date_gmt"]=>
  string(19) "2021-05-07 07:57:28"
  ["post_content"]=>
  string(0) ""
  ["post_title"]=>
  string(12) "Edit post v3"
  ["post_excerpt"]=>
  string(0) ""
  ["post_status"]=>
  string(7) "publish"
  ["comment_status"]=>
  string(4) "open"
  ["ping_status"]=>
  string(4) "open"
  ["post_password"]=>
  string(0) ""
  ["post_name"]=>
  string(11) "new-post-v3"
  ["to_ping"]=>
  string(0) ""
  ["pinged"]=>
  string(0) ""
  ["post_modified"]=>
  string(19) "2021-05-07 09:57:40"
  ["post_modified_gmt"]=>
  string(19) "2021-05-07 07:57:40"
  ["post_content_filtered"]=>
  string(0) ""
  ["post_parent"]=>
  int(0)
  ["guid"]=>
  string(31) "https://grace.open-up.it/?p=240"
  ["menu_order"]=>
  int(0)
  ["post_type"]=>
  string(4) "post"
  ["post_mime_type"]=>
  string(0) ""
  ["comment_count"]=>
  string(1) "0"
  ["filter"]=>
  string(3) "raw"
}

array(5) {
  ["unit"]=>
  string(0) ""
  ["abstract"]=>
  string(213) "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
  ["image"]=>
  string(79) "https://grace.open-up.it/wp-content/uploads/2020/10/7540312530_37e709d2f4_b.jpg"
  ["title"]=>
  string(12) "Edit post v3"
  ["url"]=>
  string(45) "https://grace.open-up.it/recipes/new-post-v3/"
}

array(2) {
  ["success"]=>
  bool(true)
  ["unit"]=>
  string(36) "e12213d3-058b-40f9-b487-a1776470f37b"
}

string(36) "e12213d3-058b-40f9-b487-a1776470f37b"

bool(true)

I really am confused about how the Wordpress editor handles the state for publishing and confused why it's not returning the meta and featured image. I found this user having the same issue(I think) with the same hook and isn't resolved either https://stackoverflow.com/questions/35666305/get-featured-image-url-after-publishing

I have also done a recording of this https://share.getcloudapp.com/eDujbqJp

I hope someone can advise or give direction regarding this. Thank you in advance

Solutions

{$new_status}_{$post->post_type} hook or publish_post fires when a post is transitioned from one status to another. At a moment this hook fires, no post meta is saved yet (on post creation).

If you need to use custom post meta, where saving callback usually attached to save_post hook, save_post also fires to soon.

I think it's better to try updated_post_meta hook, which fires immediately after updating metadata of a specific type.

I don't know if it's the Gutenberg editor or if it's the hook publish_post

The hook itself works, and if you used the old WordPress post editor, then the issue in question would not happen.

So you can say that it's the Gutenberg/block editor.

why it's not returning the meta and featured image

Because Gutenberg uses the REST API, and by the time the publish_post hook is fired (when wp_update_post() is called — see source), the post's featured image and other meta data have not yet been saved/processed.

How to fix the issue

If you're using WordPress 5.6 or later , then for what you're trying to do, you would want to use the wp_after_insert_post hook which works well with the old/classic editor and the Gutenberg/block editor.

Excerpt from https://make.wordpress.org/core/2020/11/20/new-action-wp_after_insert_post-in-wordpress-5-6/:

New action wp_after_insert_post in WordPress 5.6.

The new action wp_after_insert_post has been added to WordPress 5.6 to allow theme and plugin developers to run custom code after a post and its terms and meta data have been updated.

The save_post and related actions have commonly been used for this purpose but these hooks can fire before terms and meta data are updated outside of the classic editor. (For example in the REST API, via the block editor, within the Customizer and when an auto-draft is created.)

The new action sends up to four parameters:

  • $post_id The post ID has been updated, an integer .
  • $post The full post object in its updated form, a WP_Post object.
  • $updated Whether the post has been updated or not, a boolean .
  • $post_before The full post object prior to the update, a WP_Post object. For new posts this is null .

And here's an example which mimics the publish_post hook, i.e. the // your code here part below would only run if the post is being published and is not already published (the post status is not already publish ):

add_action( 'wp_after_insert_post', 'my_wp_after_insert_post', 10, 4 );
// Note: As of writing, the third parameter is actually named $update and not $updated.
function my_wp_after_insert_post( $post_id, $post, $update, $post_before ) {
    if ( 'publish' !== $post->post_status                           ||
        ( $post_before && 'publish' === $post_before->post_status ) ||
        wp_is_post_revision( $post_id )
    ) {
        return;
    }

    // your code here
}

Similar questions

Get first URL from custom field, download and set as featured image on post publish
I have a plugin that is adding text and a URL to a custom field when the post is published (not saved as draft). I want to get/make a function or plugin to search within the custom field and sideload the image from a URL, then add that image as the featured image. Doing some searching I found this function from another StackExchange post that was d...
Wordpress get tags in “publish_post” hook
I want to get the selected tags using publish_post hook, while publishing the post. With below code, I can get only those tags which are already saved in the post. this will not work for new tags.
Wordpress: displaying an error message - hook admin_notices fails on wp_insert_post_data or publish_post
I'm adding validation so if a post is in a particular category, it needs certain Custom Fields to be set. This should be easy hooking wp_insert_post_data and admin_notices, but there is a redirect that causes the admin_notices callback to disappear. OK - So I created a hack that uses the Session to store my error message across the redirect: The pr...
WordPress - Possible For Publish_Post Hook To Finish After Callback Finishes?
I have written a function that operates as a callback for the hook publish_post, its purpose is to check if the post has a featured image, if it does not it looks for the first image attached within that post and does some image manipulation, then sets this new manipulated image as the featured image. I know the bit of code that looks for the first...
How to get the post data which is being published on wordpress on publish_post hook?
I have written this code for using the post data which is being published on publish post hook but i don't know how to get values of the post This code gives me that post but when we update a post this function gets called again and it returns the last post but i want the post which is being updated or publish. Thanks in advance.
Wordpress Setting Featured Image Size and Adding link to featured image and Title
I've created a filterable portfolio in wordpress followindg a quicksand tutorial I found. Everything is working but the author did not link the featured image in the page template nor set the thumbnail size for the post type. I want the thumbnail size to be 280px x 180px. Here is the code: (Edited working code below)

Also ask

We use cookies to deliver the best possible experience on our website. By continuing to use this site, accepting or closing this box, you consent to our use of cookies. To learn more, visit our privacy policy .