Sometimes in a client project you’ll have a bunch of posts without a featured image but there’s some in the content, this can help grab the first image in that array of attachments for use in thumbnails etc.

Add this code to your functions.php

add_action( 'init', 'create_post_type' );
function getTheFirstImage() {
    $files = get_children('post_parent='.get_the_ID().'&post_type=attachment&post_mime_type=image');
    if($files) :
        $keys = array_reverse(array_keys($files));
        $j=0; $num = $keys[$j];
        $image=wp_get_attachment_image($num, 'large', false);
        $imagepieces = explode('"', $image);
        $imagepath = $imagepieces[1];
        echo "";

Then simply add this to the loop:


Leave a Reply