2

hi i am new on WordPress can somebody tell me how can i upload multiple images using wp_handle_upload in a loop

for($i=1;$i<count($_FILES['myfile']['name']);$i++){

    $uploadedfile = $_FILES['myfile'].$i;

    $upload_overrides = array( 'test_form'.$i => false );

    $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );

    if ( $movefile && !isset( $movefile['error'] ) ) {
      //  echo "File is valid, and was successfully uploaded.\n";

        $dir_path= $movefile['url'];


    } else {

        echo $movefile['error'];
    }
}//end loop
  • try to explane what do you need to do.. not clear what you want to achive.. and do not use $_POST of $_FILES directly inserting data to database.. always sanitize it!! – Maikal Sep 4 '15 at 11:20
  • sorry i update the code know you check again please – Hafiz Usman aftab Sep 4 '15 at 11:35
  • Still not geting.. what should be done ? what do u mean by 'update multiple meta boxes in a loop' ? here's an exaple how to upload multiple files: stackoverflow.com/questions/4178873/… – Maikal Sep 4 '15 at 11:46
  • sorry mistype i want to upload multiple images not multiple metaboxes really sorry i waste your time but please tell me how can i upload multiple images using wp_handle_upload – Hafiz Usman aftab Sep 4 '15 at 11:54
  • see the link in my prev comment, there's an marked answer wich fits your needs. – Maikal Sep 4 '15 at 11:57
4

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 );

        }
      }
    }

}
0

Hi here is code I used up in my plugin, hope you understand it and if any problem you can ask me:-

if(isset($_FILES))
    {
        for ($i=1; $i < count($_FILES) ; $i++) 
        { 

            $uploadedfile = $_FILES['question_'.$i];
            ?>
            <script type="text/javascript">
            $(document).ready(function(){
                var nam = <?php echo "question".$i; ?>
                var namm = $("."+nam).prev().attr('name');

            });
            </script>
            <?php


        $upload_overrides = array( 'test_form' => false );

        $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );

        if ( $movefile && !isset( $movefile['error'] ) ) {
            //echo "File is valid, and was successfully uploaded.\n";
            $filename = $movefile['file'];
        } else {
            /**
             * Error generated by _wp_handle_upload()
             * @see _wp_handle_upload() in wp-admin/includes/file.php
             */
            echo $movefile['error'];
        }

        // $filename should be the path to a file in the upload directory.
        //$filename = '/path/to/uploads/2013/03/filename.jpg';


        // Get the path to the upload directory.
        $wp_upload_dir = wp_upload_dir();

        $url = $wp_upload_dir['url'] . '/' . basename( $filename );
        echo $url."<br>";

    }           
    }

Here is my html code:-

    $question =get_post_meta($trivia->ID,'question',true);

     $c = 0;
     $id = uniqid();
    if ( count( $question ) > 0 ) {
        if(is_array($question)){

        foreach( $question as $questions ) {
            if ( isset( $questions['question'] ) ) {


                printf('<p>Question: <input type="text" name="question[%1$s][question]" value="%2$s"> -- <span class="remove_question">%3$s</span><span class="add_answer">   Add Answer</span></p>',   $c,$questions['question'],__('Remove Question'));
                for($i = 1; $i<=count($questions['answers']); $i++)
                {
                    if($questions['answers'][$i]['image'])
                    {
                        printf('<p>Option %5$s <input type="text" value="%1$s" name="question[%4$s][answers][%5$s][answer]"> Status <input type="text" value="%2$s" name="question[%4$s][answers][%5$s][status]"> Image <input type="text" name="question[%4$s][answers][%5$s][image]" value="%6$s"><img src="%6$s" height="100" widht="100"> -- <span class="remove_answer">%3$s</span></p>', $questions['answers'][$i]['answer'] ,$questions['answers'][$i]['status'], __('Remove Answer'), $c, $i,$questions['answers'][$i]['image']);
                    }
                    else
                    {
                        printf('<p>Option %5$s <input type="text" value="%1$s" name="question[%4$s][answers][%5$s][answer]"> Status <input type="text" value="%2$s" name="question[%4$s][answers][%5$s][status]"> -- <span class="remove_answer">%3$s</span></p>', $questions['answers'][$i]['answer'] ,$questions['answers'][$i]['status'], __('Remove Answer'), $c, $i);
                    }
                }
                $c = $c +1;
            }
        }
    }
}
 ?>
<span id="question_here"></span>
<span class="add_question"><?php _e('Add Question'); ?></span>
<script>
    var $ =jQuery.noConflict();
    $(document).ready(function() {
        var count = <?php echo $c; ?>;
         var countt = 0;
        $(".add_question").click(function() {
            count = count + 1;
            countt = 0;
            $('#question_here').append('<p>Question: <input type="text" name="question['+count+'][question]" value=""> -- <span class="remove_question">Remove question</span><span class="add_answer"> Add Answer</span></p>' );
            return false;
        });
        $(".remove_question").live('click', function() {
            $(this).parent().remove();
        });


        $(".add_answer").live('click',function(){
            countt = countt + 1;
            $('#question_here').append('<p>Answer <input type="text" name="question['+count+'][answers]['+countt+'][answer]"> Status <input type="text" name="question['+count+'][answers]['+countt+'][status]"><input id="question_'+count+'_answers_'+countt+'_image" type="text" size="36" name="question['+count+'][answers]['+countt+'][image]" value="" /><input class="upload_image_button" type="button" value="Upload Image" /><span class="remove_answer">Remove</span></p>');
        })
         $('.upload_image_button').live('click',function() {
         formfield = $('#upload_image').attr('name');
         tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');

         return false;
        });

         window.send_to_editor = function(html) {
         imgurl = $('img',html).attr('src');
         $('#question_'+count+'_answers_'+countt+'_image').val(imgurl);
         tb_remove();
        }
        $(".remove_answer").live('click', function() {
            $(this).parent().remove();
        });

    });
    </script>
</div><?php
  • your code doesn't solves, if i understood corectly, the question. Is i understood he has multiple attr in input.. – Maikal Sep 4 '15 at 12:12
  • Yes he needs this only, try to understand my code, then say anything.. – dev Sep 4 '15 at 12:15
  • i do understand your code.. in html you have something like: <input type="file" name"question_1" /><input type="file" name"question_2" /> atc., but he has <input type="file" name"questions" multiple /> and thats big difference in php whan handling upload.. – Maikal Sep 4 '15 at 12:25
  • please send your html code also i want to see your technique – Hafiz Usman aftab Sep 4 '15 at 12:26
  • I have updated my code with html..@HafizUsmanaftab – dev Sep 4 '15 at 12:33

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.