Skip to content

Instantly share code, notes, and snippets.

@mitogh
Last active September 19, 2017 19:11
Show Gist options
  • Save mitogh/4406140f09e7f6a51bf492d7205f5bb2 to your computer and use it in GitHub Desktop.
Save mitogh/4406140f09e7f6a51bf492d7205f5bb2 to your computer and use it in GitHub Desktop.
Upload assets to Wordpress
<?php
function upload_asset( $location, $post_id ) {
$timeout_seconds = MINUTE_IN_SECONDS * 10;
$tmp_file = download_url( $location, $timeout_seconds );
if ( is_wp_error( $tmp_file ) ) {
@unlink( $tmp_file );
return false;
}
$type = wp_check_filetype( $tmp_file );
if ( is_null( $type ) ) {
@unlink( $tmp_file );
return false;
}
$file = [
'name' => basename( $location ),
'tmp_name' => $tmp_file,
];
$attachment_id = media_handle_sideload( $file, $post_id );
if ( $attachment_id ) {
return $attachment_id;
} else {
@unlink( $tmp_file );
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment