Created
August 29, 2024 02:42
-
-
Save kingkool68/daa46cd2f1d8ed93b0b94425926469e1 to your computer and use it in GitHub Desktop.
Maybe sideload an image URL? This function will download an image URL to your media library but it will only do it if the URL hasn't been downloaded before.
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 | |
/** | |
* Given a URL to an image maybe sideload into the media library | |
* | |
* @param string $url The URL to sideload into the media library | |
* @param string $name The title to associate with the image | |
* @param integer $associated_post_id The post ID to associate the sideloaded image to | |
*/ | |
function maybe_sideload_image( $url = '', $name = '', $associated_post_id = 0 ) { | |
require_once ABSPATH . 'wp-admin/includes/media.php'; | |
require_once ABSPATH . 'wp-admin/includes/file.php'; | |
require_once ABSPATH . 'wp-admin/includes/image.php'; | |
// Check if the URL has previously been sideloaded | |
$media_args = array( | |
'post_type' => 'attachment', | |
'post_mime_type' => 'image', | |
'post_status' => 'inherit', | |
'posts_per_page' => 10, | |
'meta_key' => '_source_url', | |
'meta_value' => $url, | |
'no_found_rows' => true, | |
'update_post_meta_cache' => false, | |
'update_post_term_cache' => false, | |
'fields' => 'ids', | |
); | |
$posts = get_posts( $media_args ); | |
if ( ! empty( $posts[0] ) ) { | |
return $posts[0]; | |
} | |
$associated_post_id = absint( $associated_post_id ); | |
$created_post_id = media_sideload_image( $url, $associated_post_id, $name, 'id' ); | |
if ( is_wp_error( $created_post_id ) ) { | |
$created_post_id = 0; | |
} | |
return absint( $created_post_id ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment