Paulund
2016-03-22 #wordpress

Get WordPress Image ID By URL

In a recent project I needed to automatically assign a image to a post from a URL. This situation happened where I had a library of image URLs which on the publish event of a new WordPress post we needed to check that the post had a featured image, if it didn't have a featured image then we automatically assign a image to this post. Therefore I had an array of image URLs we will use to randomly select an image to use as the featured image on the post. To programmatically assign an image to a post as the featured image you need to use the function set_post_thumbnail(), which takes two parameters a post ID and the attachment ID.


set_post_thumbnail( $postId, $attachmentId );

In WordPress a image that is added to the media library is called an attachment, so to add an image as the featured image on a post it first needs to be added to the media library before we can assign it to a post. In this situation I know that all the images in the array are added to the media library we just need to get the attachment ID to assign it to the post. When an image is added to the media library it's classed as a attachment, which is added to the wp_posts table with a post type of attachment. This means to get the ID of the image we can simply query the wp_posts table for the image on the guid column.

SELECT ID FROM $wpdb->posts WHERE guid = $imageUrl

As we only need the ID column then we can use the method get_col to make sure we only return this post ID.


function getImageIdByUrl( $url )
{
    global $wpdb;
    $image = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $url ));
        
    if(!empty($image))
    {
        return $image[0];    
    }
        
    return false;
}

The problem you'll find with the above function is that it will not find IDs for images if the URL is for a auto generated thumbnail. Auto generated thumbnail URLs are created by WordPress when you upload an image it will create multiple images with the different sizes of your media items. To find this image in the wp_posts you need to remove the sizes from the URL before searching the guid column on the wp_posts.


function getImageIdByUrl( $url )
{
    global $wpdb;

    // If the URL is auto-generated thumbnail, remove the sizes and get the URL of the original image
    $url = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $url );

    $image = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $url ));

    if(!empty($image))
    {
        return $image[0];
    }

    return false;
}

If we get an image returned from this function we can then use this to add a featured image to the post using the set_post_thumbnail() function.


// Check the array is populated with featured images
if(!empty($featuredImages))
{
    // Get random picture from remaining images
    $randomPicture = array_rand($featuredImages, 1);
    
    // Get an attachment ID of the featured image
    $attachmentId = getImageIdByUrl($featuredImages[$randomPicture]);

    // Check if attachment ID is not false
    if($attachmentId)
    {
        set_post_thumbnail( $post_id, $attachmentId );
    }
}