Upload Image WordPress Media Library programmatically

This tutorial explains how to Upload Image to Wordpress Media Library programmatically. Here I am showing how to bulk upload images to the wordpress media library.

The upload images are assigning to the ACF image repeater field as show above. Please click here to find how to get all images from the folder in an array.

upload_images_to_wordpress_media_library

function uploadImages( $files ) {

    $imgAcfIds = array();

    foreach($files as $imgfile) {
        $filename = basename($imgfile);
        $upload_file = wp_upload_bits($filename, null, file_get_contents($imgfile));
        if (!$upload_file['error']) {
            $wp_filetype = wp_check_filetype($filename, null );
            $attachment = array(
                'post_mime_type' => $wp_filetype['type'],
                'post_parent' => 251,
                'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
                'post_content' => '',
                'post_status' => 'inherit'
            );
            $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], 251 );

            // get attachment id for acf field

            $imgAcfIds[] = array('product_image' => $attachment_id);
            echo 'Attachment Id :'.$attachment_id .PHP_EOL;
            if (!is_wp_error($attachment_id)) {
                require_once(ABSPATH . "wp-admin" . '/includes/image.php');
                $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
                wp_update_attachment_metadata( $attachment_id,  $attachment_data );
            }
        }
    }
    //echo '<pre>';
    //print_r($imgAcfIds);
    update_field( 'field_5985046a78782', $imgAcfIds , 251 );
}

Share this Tutorial