-
-
Save tomjn/704af972249c5c39a576 to your computer and use it in GitHub Desktop.
Attaching a file already in place
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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