Last active
September 19, 2017 19:11
-
-
Save mitogh/4406140f09e7f6a51bf492d7205f5bb2 to your computer and use it in GitHub Desktop.
Upload assets to Wordpress
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 | |
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