tomas
tomas

Reputation: 739

WordPress file "upload" from plugin

I'm trying to create plugin importing posts to WordPress. Imported articles (XML) contain "image-name" attribute and this image is already uploaded to the server.

I would like to, however, make WordPress do its "magic" and import the image to the system (create thumbnails, attach it to the post, place it under the wp-uploads directory scheme)... I found function media_handle_upload($file_id, $post_id, $post_data, $overrides) but it requires array $_FILES to be filled with actual upload (and I'm not uploading file - it is already placed on the server) so it's not very useful

Do you have any hint how to proceed?

Thanks

Upvotes: 1

Views: 888

Answers (1)

tamilsweet
tamilsweet

Reputation: 1007

Check the following script to get the idea. (It does work.)

    $title = 'Title for the image';
    $post_id = YOUR_POST_ID_HERE; // get it from return value of wp_insert_post
    $image = $this->cache_image($YOUR_IMAGE_URL);
    if($image) {
        $attachment = array(
            'guid' => $image['full_path'],
            'post_type' => 'attachment',
            'post_title' => $title,
            'post_content' => '',
            'post_parent' => $post_id,
            'post_status' => 'publish',
            'post_mime_type' => $image['type'],
            'post_author'   => 1
        );

        // Attach the image to post
        $attach_id = wp_insert_attachment( $attachment, $image['full_path'], $post_id );
        // update metadata
        if ( !is_wp_error($attach_id) )
        {
            /** Admin Image API for metadata updating */
            require_once(ABSPATH . '/wp-admin/includes/image.php');
            wp_update_attachment_metadata
            ( $attach_id, wp_generate_attachment_metadata
            ( $attach_id, $image['full_path'] ) );
        }
    }

function cache_image($url) {
    $contents = @file_get_contents($url);
    $filename = basename($url);
    $dir = wp_upload_dir();
    $cache_path = $dir['path'];
    $cache_url = $dir['url'];

    $image['path'] = $cache_path;
    $image['url'] = $cache_url;

    $new_filename = wp_unique_filename( $cache_path, $filename );
    if(is_writable($cache_path) && $contents)
    {
        file_put_contents($cache_path . '/' . $new_filename, $contents);

        $image['type'] = $this->mime_type($cache_path . '/' . $new_filename); //where is function mime_type() ???

        $image['filename'] = $new_filename;
        $image['full_path'] = $cache_path . '/' . $new_filename;
        $image['full_url'] = $cache_url . '/' . $new_filename;
        return $image;
    }
    return false;
}

Upvotes: 2

Related Questions