Skip to main content
5 of 6
added 4 characters in body
Wyck
  • 18k
  • 4
  • 46
  • 67

This script is a proof of concept (tested and working), it is not a plugin and is meant to be hacked with, it assumes a few things:

  1. It uses wp_insert_post so it's advised you do not hook it into any admin hooks, so just run it once!
  2. The images must be in the wp-content\uploads folder, changing this would require more hoops to jump through. The example uses a custom folder called \images in the uploads folder, you can change this part.
  3. It does not do any error checking, I only tested it on a folder with 20 images so results might vary:)

The code below will iterate through the wp-content\uploads\images folder and create a post title based on the name of the image being attached to it. You probably want to change this to something better or possible enter meta data using other data you have (Exif maybe).

function WPSE_1595_image_post() {

    // We need to use the default uploads dir
    $wp_upload_dir =  wp_upload_dir();
    // The actual folder
    $wp_upload_images = $wp_upload_dir['basedir'] . '/images';
    
    require_once(ABSPATH . 'wp-admin/includes/image.php');

    foreach (new DirectoryIterator($wp_upload_images) as $fileInfo) {

        if($fileInfo->isDot()) continue;
        
        $image_base = $fileInfo->getFilename();
        $image_name = pathinfo($fileInfo, PATHINFO_FILENAME);

        //Customize this post data as you wish
        $my_post_data = array(
            'post_title' => $image_name,
            'post_type' => 'post',
            'post_category' => array('1'),
            'post_author'   => 1,
            'post_status' => 'publish'
        );

        wp_insert_post( $my_post_data);
        // We need the ID for the attachment
        $post_id = wp_insert_post($my_post_data);

        $wp_filetype = wp_check_filetype($image_base, null );
  
         //Customize this attachment data as you wish
        $attachment = array(
             'guid' => $wp_upload_dir['url'] . '/' . $image_name, 
             'post_mime_type' => $wp_filetype['type'],
             'post_title' => 'child-' . $image_name,
             'post_content' => '',
             'post_status' => 'inherit'
        );

        $imagefile = $wp_upload_images . '/' . $image_base;
        $attach_id = wp_insert_attachment( $attachment, $imagefile, $post_id );
        $attach_data = wp_generate_attachment_metadata( $attach_id, $imagefile );

        wp_update_attachment_metadata( $attach_id, $attach_data );
    }   
}

For anything over a few thousand images you would probably have an easier time using:

Wyck
  • 18k
  • 4
  • 46
  • 67