how to upload image using wp_handle_upload

here’s my example of how to upload multiple images:

add_action( 'add_meta_boxes',   'my_test_metabox' );

function my_test_metabox() {
    add_meta_box( 'my_test_metabox', 'File upload', 'my_test_metabox_out', 'post' );
}

add_action('post_edit_form_tag', 'update_edit_form' );
function update_edit_form() {
    echo ' enctype="multipart/form-data"';
}

function my_test_metabox_out( $post ) {

    $files = get_post_meta( $post->ID, 'my_files', true );
    if( ! empty( $files ) ) {
        echo 'Files uploaded:' . "\r\n";
        foreach( $files as $file ) {
            echo '<img src="' . $file['url'] . '" width="100" height="100" />';
        }
        echo "\r\n";
    }
    echo 'Upload files:' . "\r\n";
    echo '<input type="file" name="my_files[]" multiple />';

}

add_action( 'save_post', 'my_files_save' );

function my_files_save( $post_id ) {

    if( ! isset( $_FILES ) || empty( $_FILES ) || ! isset( $_FILES['my_files'] ) )
        return;

    if ( ! function_exists( 'wp_handle_upload' ) ) {
        require_once( ABSPATH . 'wp-admin/includes/file.php' );
    }
    $upload_overrides = array( 'test_form' => false );

    $files = $_FILES['my_files'];
    foreach ($files['name'] as $key => $value) {
      if ($files['name'][$key]) {
        $uploadedfile = array(
            'name'     => $files['name'][$key],
            'type'     => $files['type'][$key],
            'tmp_name' => $files['tmp_name'][$key],
            'error'    => $files['error'][$key],
            'size'     => $files['size'][$key]
        );
        $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );

        if ( $movefile && !isset( $movefile['error'] ) ) {
            $ufiles = get_post_meta( $post_id, 'my_files', true );
            if( empty( $ufiles ) ) $ufiles = array();
            $ufiles[] = $movefile;
            update_post_meta( $post_id, 'my_files', $ufiles );

        }
      }
    }

}

Leave a Comment