Wordpress - Retrieve featured image

The featured image attachment id is stored in the post_meta table, with the meta_key _thumbnail_id.

Use that post id to find the post meta with meta_key _wp_attachment_metadata.

The value of that is a serialized array with keys thumb, file, width, height, sizes (an array), and image_meta (an array).

The file value is relative to the uploads directory for the WP install, and points to the original full-sized image. You should be able to calculate the URL from that.

sizes has an image size as its key (e.g., 'small', 'medium', 'large', 'thumbnail'), and the value is an array with keys file, height, and width.

image_meta will contain things like exif/iptc image metadata from the image itself.


The post thumbnail is a stored in the {$wpdb->prefix}_postmeta table with the key _thumbnail_id.

Something like this:

SELECT * from {$wpdb->prefix}_posts 
WHERE ID in (
   SELECT meta_value FROM {$wpdb->prefix}_postmeta 
   WHERE meta_key = '_thumbnail_id'
   AND post_id = ':ID'
);

Replace :ID with the post id.

That will return the Post associated with the image itself -- the post_title will be whatever the user associated with the title attribute on the image, and the guid will be the full sized image URL.

If you want different sizes, you'll have to look up the _wp_attachment_metadata postmeta value which will contain a serialized array with all the different sizes.

Using WordPress' api is much easier:

<?php
if(has_post_thumbnail($some_post_id))
{
   $img = wp_get_attachment_img_src(get_post_thumbnail_id($some_post_id), 'the_image_size');
   // returns an array, the first item is the image URL
   echo $img[0];
}

The post's featured image is a regular old attachment to the post. So, as with any other image attachment, you'll need to query the wp_posts table for a post type of attachment. The trick is to first get the attachment ID that you need to grab.

This is contained in the given post's meta information, specifically the _thumbnail_id meta.

So, you'll need a query that:

  1. Retrieves the value marked by the key _thumbnail_id in the wp_postmeta table based on a given post ID.
  2. Retrieves the attachment from the wp_posts table based on the ID retrieved in step #1
  3. Generates an attachment permalink based on the information retrieved in step #2

Really, though, you're doing a lot of work to reinvent the wheel here ...