Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Get WordPress Image ID by URL

DZone's Guide to

Get WordPress Image ID by URL

In a recent project, I needed to automatically assign an image to a post from a URL. So, how did we solve this problem? Read on to find out.

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

In a recent project, I needed to automatically assign an image to a post from a URL. The 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 an image to this post.

Therefore, I had an array of image URLs we used 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, an 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, and 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 an 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 an 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 );
    }
}

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
wordpress ,images

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}