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.

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.