Skip to content

Instantly share code, notes, and snippets.

@tomjn
Created Aug 20, 2012
Embed
What would you like to do?
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