0

I am submitting an image to the db like this:

if (isset($_POST['uploadImgCustom'])) {
    $myNewImg = get_post_meta($id, 'usp-file-single', true);
}
$attachments = get_posts(array( 
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' =>'any',
    'post_parent' => $post->ID
));

if ($attachments) {
    foreach ( $attachments as $attachment ) {
        $myNewImg = wp_get_attachment_url( $attachment->ID );
        update_post_meta( $id, 'usp-file-single', $myNewImg);
    } 
?>
    <img src="<?php echo $myNewImg; ?>" class="img-responsive">
<?php }

And then I do:

if($_SERVER['REQUEST_METHOD']=="POST") {
    if ('AGGIORNA ALLEGATO' === ($_POST['uploadImgCustom'])) {
        if ($_FILES['postImage']) {
            $attachments = get_attached_media( '', $id );
            foreach ($attachments as $attachment) {
                wp_delete_attachment( $attachment->ID, 'true' );
            }   
            foreach ($_FILES as $file => $array) {
                if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
               //Add your error action
                } else {    
                    $attach_id = media_handle_upload( $file, $id );
                }
            }   
        }
    }
}

The new file is uploaded correctly and the page refreshes itself after upload completed. Yet I am seeing the old image on the page, however if I refresh the page, I see the new file. It is like keeping the cache and not reading the new data at first.

The following it is the current post ID which I grab at the beginning of the code right after I start the loop.

$id = get_the_ID();

The form html is the following:

<div class="row">
    <div class="col-xs-12">
        <h3>CARICA UNA NUOVA IMMAGINE O VIDEO</h3>
        <form method="POST" action="" enctype="multipart/form-data">
            <div class="form-group">
                <input type="file" name="postImage" multiple="multiple" class="form-control">
            </div>
            <input id="uploadImg" name="uploadImgCustom" type="submit" value="AGGIORNA ALLEGATO" class="btn secondary-btn primary-bg">
        </form>
    </div>
</div>
0

This is how I resolved it:

$myNewImg = get_post_meta($id, 'usp-file-single', true);
if (isset($_POST['uploadImgCustom'])) {
    $myNewImg = $_POST['uploadImgCustom'];
}
$attachments = get_posts(array(.... 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.