DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • How to Use AI With WordPress
  • Spring Boot GoT: Game of Trace!
  • Using a Body With an HTTP Get Method Is Still a Bad Idea

Trending

  • Event-Driven Microservices: How Kafka and RabbitMQ Power Scalable Systems
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • Apple and Anthropic Partner on AI-Powered Vibe-Coding Tool – Public Release TBD
  • The End of “Good Enough Agile”

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.

By 
Paul Underwood user avatar
Paul Underwood
·
Mar. 28, 16 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
10.8K Views

Join the DZone community and get the full member experience.

Join For Free

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 );
    }
}
WordPress POST (HTTP)

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

Opinions expressed by DZone contributors are their own.

Related

  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • How to Use AI With WordPress
  • Spring Boot GoT: Game of Trace!
  • Using a Body With an HTTP Get Method Is Still a Bad Idea

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!