Skip to content

Instantly share code, notes, and snippets.

@aliboy08
Last active October 18, 2018 00:54
Show Gist options
  • Save aliboy08/ccf439ac3ea37190845e41aae77ea0ee to your computer and use it in GitHub Desktop.
Save aliboy08/ccf439ac3ea37190845e41aae77ea0ee to your computer and use it in GitHub Desktop.
Check if image exists in the WP database, return id if found
function ff_get_image_id_by_url($image_url, $type = 'full') {
global $wpdb;
if( $type === 'full' ) {
// Search url
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
} else {
// Search name using LIKE
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid LIKE '%s';", '%' . $wpdb->esc_like($image_url) . '%' ));
}
if( $attachment )
return $attachment[0];
}
function ff_upload_and_attach_image_to_post( $image_url, $post_id ){
// Check if image file exists
if (@getimagesize($image_url)) {
$set_image = false;
$image_url = trim($image_url);
if (strpos($image_url, $_SERVER['SERVER_NAME']) !== false) {
// Internal source, search db for image url
$check_image = ff_get_image_id_by_url($image_url, 'full');
} else {
// External source, search db for file name
$image_name = wp_basename($image_url);
// remove query strings:
$remove_query_strings = explode('?', $image_name);
$image_name = $remove_query_strings[0];
$check_image = ff_get_image_id_by_url($image_name, 'filename');
}
if( $check_image ) {
// Image already exists, get id
$set_image = $check_image;
} else {
// Image does not exist in the site, download and upload the new image to the site
$set_image = media_sideload_image($image_url, $post_id, '', 'id');
}
if( $set_image ) {
// Set post featured image
set_post_thumbnail( $post_id, $set_image );
}
} else {
// No image set
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment