Sometimes you don’t have a featured image with your post. In such a case you would like to have the first image of the post as thumbnail . Here is a snippet to get the first image from post content. sometimes this trick might not work, this occurs when the DOM element has a different structure. So if this doesn’t work for some reason, try adding one more regex which suits your case to make it work. You can also parse the DOM to get the image source. I will cover that topic in the next post. For now, here is how you do it through regex.
function catch_that_image ($post_id=0, $width=60, $height=60, $img_script='') { // you can set any params here global $wpdb; if($post_id > 0) { // select the post content from the db $sql = 'SELECT post_content FROM ' . $wpdb->posts . ' WHERE id = ' . $wpdb->escape($post_id); $row = $wpdb->get_row($sql); $the_content = $row->post_content; if(strlen($the_content)) { // use regex to find the src of the image preg_match("/<img src\=('|\")(.*)('|\") .*( |)\/>/", $the_content, $matches); if(!$matches) { preg_match("/<img class\=\".*\" src\=('|\")(.*)('|\") .*( |)\/>/U", $the_content, $matches); } if(!$matches) { preg_match("/<img class\=\".*\" title\=\".*\" src\=('|\")(.*)('|\") .*( |)\/>/U", $the_content, $matches); } $the_image = ''; $the_image_src = $matches[2]; $frags = preg_split("/(\"|')/", $the_image_src); if(count($frags)) { $the_image_src = $frags[0]; } // if an image isn't found yet if(!strlen($the_image_src)) { $attachments = get_children( array( 'post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ); if (count($attachments) > 0) { $q = 0; foreach ( $attachments as $id => $attachment ) { $q++; if ($q == 1) { $thumbURL = wp_get_attachment_image_src( $id, $args['size'] ); $the_image_src = $thumbURL[0]; break; } // if first image } // foreach } // if there are attachments } // if no image found yet // if src found, then create a new img tag if(strlen($the_image_src)) { if(strlen($img_script)) { // if the src starts with http/https, then strip out server name if(preg_match("/^(http(|s):\/\/)/", $the_image_src)) { $the_image_src = preg_replace("/^(http(|s):\/\/)/", '', $the_image_src); $frags = split("\/", $the_image_src); array_shift($frags); $the_image_src = '/' . join("/", $frags); } $the_image = '<img alt="" src="' . $img_script . $the_image_src . '" />'; } else { $the_image = '<img alt="" src="' . $the_image_src . '" width="' . $width . '" height="' . $height . '" />'; } } return $the_image_src; } } }
In html you will call the function as
$img=catch_that_image($post->ID); <img src="<?php echo $img" title="" />
Another way of doing that is by the code provided at codex
function echo_first_image ($postID) { $args = array( 'numberposts' => 1, 'order'=> 'ASC', 'post_mime_type' => 'image', 'post_parent' => $postID, 'post_status' => null, 'post_type' => 'attachment' ); $attachments = get_children( $args ); //print_r($attachments); if ($attachments) { foreach($attachments as $attachment) { $image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) ? wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) : wp_get_attachment_image_src( $attachment->ID, 'full' ); echo '<img src="'.wp_get_attachment_thumb_url( $attachment->ID ).'" class="current">'; } } }
To use this code, you just need to call the function like this
echo_first_image($post->ID); //this displays the image, i haven't tested this myself though
This is another very smart method of extracting the first image. I found this one the best since it directly extracts the source attribute and does not look for specific patterns in html. Use the code below in your functions.php
function ax_extract_string($start, $end, $original) { $original = stristr($original, $start); $trimmed = stristr($original, $end); return substr($original, strlen($start), -strlen($trimmed)); } function catch_that_image($postid) { $content = get_the_content($postid); $pic_source = ax_extract_string('src="','" ',$content); return $pic_source; }
Now use it anywhere in your template files as
<img src='<?php echo catch_that_image($post->id); ?>' alt='' />
Hope you liked these snippets and tricks.
2 comments
Eric
December 19, 2012 at 2:42 pm
Great post! I particularly like your ax_extract_string() solution because it requires no patterns which may fail. Thanks for posting!
Riccardo
April 6, 2013 at 5:54 pm
Thanks you, very useful!