Skip to content

Instantly share code, notes, and snippets.

@tomjn
Created August 20, 2012 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomjn/704af972249c5c39a576 to your computer and use it in GitHub Desktop.
Save tomjn/704af972249c5c39a576 to your computer and use it in GitHub Desktop.
Attaching a file already in place
<?php
$url = home_url().'/wp-content/uploads/yourfilehere.jpg';
$type = 'image/jpeg';
$file = ABSPATH.'/wp-content/uploads/yourfilehere.jpg';
$title = preg_replace('/\.[^.]+$/', '', basename($file));
$content = '';
$parent_id = 0;
// use image exif/iptc data for title and caption defaults if possible
if ( $image_meta = @wp_read_image_metadata($file) ) {
if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) )
$title = $image_meta['title'];
if ( trim( $image_meta['caption'] ) )
$content = $image_meta['caption'];
}
if ( isset( $desc ) )
$title = $desc;
// Construct the attachment array
$attachment = array(
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => $parent_id,
'post_title' => $title,
'post_content' => $content
);
// Save the attachment metadata
$id = wp_insert_attachment($attachment, $file, $parent_id);
if ( !is_wp_error($id) )
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment