Some day ago I worked on a professional theme with a lot of features and a slider on home page. That slider was fully configurable but it was searching post images looking “only” to the post featured image.

Of course the blog using that theme had not featured images set on posts. Hence the slider was not working at all.

Even to generate thumbnails for post list the theme was using the featured image producing category pages really poor.

The solution without touching a single post (and fully revertible) is to add a filter so the feature image seems to be present even if it is not. The filter is about a metadata function called to search for the featured image id, get_metadata() and located on meta.php file.

The filter is simple: it intercepts the call to metadata looking if it’s called with a meta key related to the featured image and if that image if not selected extracting the first image of the post gallery.

Here the code:

add_filter('get_post_metadata', 'pf_get_post_metadata', 10, 4);
function pf_get_post_metadata($null, $object_id, $meta_key, $single) {
    global $wpdb;

    if ($meta_key != '_thumbnail_id') return null;
    $res = $wpdb->get_var($wpdb->prepare("SELECT post_id, meta_key, meta_value FROM $table WHERE $post_id=%d and meta_key=%s", $object_id, $meta_key));
    if ($res) return null;
    $attachments = get_children(array('post_parent'=>$object_id, 'post_status'=>'inherit', 'post_type'=>'attachment', 'post_mime_type'=>'image', 'order'=>'ASC', 'orderby'=>'menu_order ID'));

    if (empty($attachments)) return null;

    foreach ($attachments as $id => $attachment) {
        return $id;

    return null;


The first line checks if the meta key asked is the one identify the featured image (_thumbnail_id).
If that is the key, we must check if it exists between the post metadata and if present we don’t need to simulate it. Note that the check is made with a direct query since calling metadata retrieving functions may create an infinite loop calling recursively our filter.

If the featured images metadata is not present, we load all the images associated to the post and we take the first one using it as featured image.

The “get_children” call can be eventually changed to search for attachment in a different order. That’s all.

Please note that this code has been tested on WordPress 3.5.1 and not in an extensive mode.

Similar Posts


  1. After importing a blog to WordPress, I needed to set the featured image for many, many posts. I used a plugin called “Bulk-Select Featured Image”. Basically, I just did manually exactly this: set the first image in the post as featured image. It’s a pity I didn’t find this post earlier, it’d have saved me a lot of time…

Leave a Reply