How to get an image transferred via FTP or script to appear in Media Manager?

I’ve got a plugin that transfers some files over to the uploads folder of the site in which the plugin is installed.

It works fine, however, the images are not appearing in the Media Manager. I expect some database registration is involved.

Given the script below which copies the files into the directory, what command would I need to add to the loop to register each image for the media manager?

    foreach(new RecursiveIteratorIterator($rdi) as $files) 
    {
         if ($files->isFile()) 
         {
            $imagepath = $files->getRealPath();
            $image = basename($files->getPathname());
            copy($imagepath, $my_target_folder."https://wordpress.stackexchange.com/".$image);
         }
    }

2 Answers
2

add this to your for each and $filename to each file,

 $wp_filetype = wp_check_filetype(basename($filename), null );
  $attachment = array(
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
     'post_content' => '',
     'post_status' => 'inherit'
  );
  $attach_id = wp_insert_attachment( $attachment, $filename, 0 );
  // you must first include the image.php file
  // for the function wp_generate_attachment_metadata() to work
  require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
  wp_update_attachment_metadata( $attach_id,  $attach_data );

Leave a Comment