Skip to content

Instantly share code, notes, and snippets.

@isotrope
Created September 23, 2014 14:55
Show Gist options
  • Save isotrope/dff1bb0144514d15567e to your computer and use it in GitHub Desktop.
Save isotrope/dff1bb0144514d15567e to your computer and use it in GitHub Desktop.
Add files to library, pull in from outside
<?php
function iso_add_file( $post_id, $url ) {
$temp_file = download_url( $url, 500 );
if ( ! is_wp_error( $temp_file ) ) {
$file_type = wp_check_filetype( $temp_file );
// array based on $_FILE as seen in PHP file uploads
$file = array(
'name' => basename( $url ), // ex: wp-header-logo.png
'type' => $file_type['type'],
'tmp_name' => $temp_file,
'error' => 0,
'size' => filesize( $temp_file ),
);
$overrides = array(
// tells WordPress to not look for the POST form
// fields that would normally be present, default is true,
// we downloaded the file from a remote server, so there
// will be no form fields
'test_form' => false,
// setting this to false lets WordPress allow empty files, not recommended
'test_size' => true,
// A properly uploaded file will pass this test.
// There should be no reason to override this one.
'test_upload' => true,
);
// move the temporary file into the uploads directory
$results = wp_handle_sideload( $file, $overrides );
if ( ! empty( $results['error'] ) ) {
// insert any error handling here
return false;
} else {
$filename = $results['file']; // full path to the file
$local_url = $results['url']; // URL to the file in the uploads dir
$type = $results['type']; // MIME type of the file
// perform any actions here based in the above results
echo '
<pre>';
echo '--------------------------------------------------------';
var_dump( $results );
echo '</pre>';
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $results['file'],
'post_mime_type' => $results['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
//require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
echo 'Inserted as ' . $attach_id;
echo '--------------------------------------------------------';
return $attach_id;
}
} else {
echo 'Something went wrong with ' . $url;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment