Cannot get featured image after Publish but works fine after Update

339 Views Asked by At

I have a WordPress hook: add_action( 'publish_post', 'post_published_notification', 10, 2 );

When publishing I am unable to get the featured image. I have tried many different methods to no avail. After the initial publishing of an article I get '0' for the thumbnail id but after editing and clicking update I get all the correct values.

Hook looks like this:

function post_published_notification( $post_id, $post ) {
    $post_status = get_post_status( $post_id ); //always returns "publish"
    $title = $post->post_title; //works correctly always
    $permalink = get_permalink( $post_id ); //works correctly always
    $excerpt = get_the_excerpt($post); //works correctly always
    //All three variables below are empty when publishing a post but assign correctly when updating an existing post
    $image = get_the_post_thumbnail_url( $post_id, 'medium' );
    $image2 = get_the_post_thumbnail_url($post_id, 'article-thumbnail-image');
    $image3 = get_post_meta( get_post_meta( $post_id, "_thumbnail_id", true ), "_wp_attached_file", true );
    
    $thumb_id = get_post_thumbnail_id( $post_id ); //returns 0 on publish; Correct Id on update
    
    
}
1

There are 1 best solutions below

0
JMWalker On

Try using the "wp_after_insert_post" hook.

add_action( 'wp_after_insert_post', 'after_insert_post', 10, 4 );

function 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;
    }
    $image_url = get_the_post_thumbnail_url($post_id);
}