We are building an Android app based on a WordPress mysql database. We were able to get most of the information from the datase to display on to the app. Now all we have left is to retrieve the posts featured image.
Is there a way to have the featured image output a URL?
Thanks!
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), andimage_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 keysfile
,height
, andwidth
.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:
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 theguid
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:
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 ofattachment
. 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:
_thumbnail_id
in thewp_postmeta
table based on a given post ID.wp_posts
table based on the ID retrieved in step #1Really, though, you’re doing a lot of work to reinvent the wheel here …
Here’s what I used to retrieve post data, featured image URL and feature image details (such as dimensions):
Use next query to retrieve the featured images of all posts:
The best SQL solution,
Search the ID from wp_post
SELECT * FROM wp_posts WHERE post_status='publish'
Found the meta content
SELECT * FROM wp_postmeta WHERE meta_key='_thumbnail_id' AND post_id=MyID
With the thumbnail ID, search one more time into wp_postmeta the file
Here one example.