Created
February 7, 2014 15:51
-
-
Save annalinneajohansson/98994ddd9f1af8ff2ec7 to your computer and use it in GitHub Desktop.
Download and attach an external file. Skip if an attachment with that name already exists.
This file contains hidden or 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 = "url to file"; | |
$tmp = download_url( $url ); | |
/* Does a file with this name already exist in the media library? */ | |
$filename = remove_accents( preg_replace("/\\.[^.\\s]{3,4}$/", "", basename( $url ) ) ); | |
global $wpdb; | |
$poststable = $wpdb->prefix . "posts"; | |
$filename_exists = $wpdb->get_col( "SELECT post_name FROM $poststable WHERE post_name LIKE '$filename' AND post_type = 'attachment'" ); | |
if( empty( $filename_exists ) ) { | |
$file_array = array( | |
'name' => basename( $url ), | |
'tmp_name' => $tmp | |
); | |
// Check for download errors | |
if ( is_wp_error( $tmp ) ) { | |
@unlink( $file_array[ 'tmp_name' ] ); | |
return $tmp; | |
} | |
$image_id = media_handle_sideload( $file_array, $post_id ); | |
// Check for handle sideload errors. | |
if ( is_wp_error( $image_id ) ) { | |
@unlink( $file_array['tmp_name'] ); | |
return $image_id; | |
} | |
set_post_thumbnail( $current_post_id, $image_id ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment