How to add media from front-end to an existing post?

@AboSami actually answered this question in an older post that was not showing up in my search diligence. While he was actually looking for something else his example code worked great.

Here’s the script:

<?php $post_id = $post->ID;
if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) {
    require_once(ABSPATH . 'wp-admin/includes/admin.php');
    $id = media_handle_upload('async-upload', $post_id); //post id of Client Files page
    unset($_FILES);
    if ( is_wp_error($id) ) {
        $errors['upload_error'] = $id;
        $id = false;
    }

    if ($errors) {
        echo "<p>There was an error uploading your file.</p>";
    } else {
        echo "<p>Your file has been uploaded.</p>";
    }
}

?>
    <form id="file-form" enctype="multipart/form-data" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST">

    <p id="async-upload-wrap"><label for="async-upload">upload</label>
    <input type="file" id="async-upload" name="async-upload"> <input type="submit" value="Upload" name="html-upload"></p>

    <p><input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id ?>" />
    <?php wp_nonce_field('client-file-upload'); ?>
    <input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" /></p>

    <p><input type="submit" value="Save all changes" name="save" style="display: none;"></p>
    </form>

Leave a Comment