'Programatically updating post featured image appears on frontend only on page refresh [closed]

I am programatically updating the post thumbnail from the single post page on the frontend via a form, and also deleting the previous image and its meta data from the database before I upload the new one to keep things clutter free in the DB. Everything works fine, it's just that when the single post page gets refreshed on form submit, it still shows the old image. I have to refresh the page one more time manually to display the new featured image.

if( !empty( $_FILES['post-image']['name']) && $_FILES['post-image']['error'] == 0 ){

    $old_img_id = get_post_thumbnail_id($post_id);
    wp_delete_attachment( $old_img_id, true );
    delete_post_meta( $post_id, '_thumbnail_id'. $old_img_id );
    delete_post_thumbnail($post_id);
    
    
    $uploaddir = wp_upload_dir();
    $file = $_FILES['post-image']['name'];
    $temp = $_FILES['post-image']['tmp_name'];
    $uploadfile = $uploaddir['path'] . '/' . rand(1,1000) . basename( $file );
    
    
    move_uploaded_file( $temp , $uploadfile );
    $filename = basename( $uploadfile );
    
    $wp_filetype = wp_check_filetype(basename($filename), null );
    // echo $mime_check = $wp_filetype['ext'];
    
    
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit',
    );
    require( ABSPATH . 'wp-admin/includes/image.php' );
    require( ABSPATH . 'wp-admin/includes/file.php' );
    require( ABSPATH . 'wp-admin/includes/media.php' );
    
    
    $attach_id = wp_insert_attachment( $attachment, $uploadfile );
    set_post_thumbnail( $post_id, $attach_id ); 
    
    $metadata = wp_generate_attachment_metadata( $attach_id, $uploadfile );
    wp_update_attachment_metadata( $attach_id, $metadata );
}

And this is how I am displaying the post thumbnail on this page:

<img src="<?php if(has_post_thumbnail($post_id)) : echo "http://my-site.local/wp-content/uploads/2022/03/325business_page.jpg"; else : echo get_stylesheet_directory_uri() . '/assets/images/Image placeholder.jpg'; endif; ?>" id="uploaded_image" class="img-responsive img-circle" />

How do I get rid of this old featured image still showing on form submit even after it is supposed to have been deleted from the db? Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source