Getting the first image in a wordpress post by parsing the raw post data, better option?

I have a site that needs to display the first image from any given post in a specific category. I have it working, and have added code below. My question is, is there a better way? This seems awfully kludgy.

I’m parsing the post data for whatever first appears between src=" and ". Any gotcha’s that i’m missing? Does WordPress have a better way to do this built in?

Read More
function extractStringFromString($string, $start, $end) {
//Finds the first string between $start and $end. 

    $startPos = strpos($string,$start);

    $stringEndTagPos = strpos($string,$end,$startPos);

    $stringBetween = substr($string,$startPos+strlen($start),$stringEndTagPos-$startPos-strlen($start));

    if (strlen($stringBetween) != 0 && $startPos!= '') {
        return $stringBetween;
    }
    else {
        return false;
    }



}
function getfirstimage($post){
//Returns url of first image located in post data
global $wpdb;

$sqlquery = "SELECT post_content FROM  `wp_posts` WHERE  `ID` = $post LIMIT 0 , 1";
$result = $wpdb->get_results( $sqlquery );
$result = $result[0];
$postcontent = $result->post_content;

if ($result){
    return extractStringFromString($postcontent, 'src="', '" ');
}

else return 0;

}

Related posts

Leave a Reply

3 comments

  1. 3rd Option: Use a Dom Parser

    <?php
    while(have_posts()) : the_post();
        $dom = new DOMDocument();
        $dom->loadHTML(get_the_content());
        $images = $dom->getElementsByTagName('img');
        $src = $images->item(0)->getAttribute('src');
        echo 'Src: '.$src.'<br/>';
        echo 'First Image: '.$images->item(0)->saveHTML();
        echo 'Image HTML: '.htmlentities($images->item(0)->saveHTML());
    endwhile;
    ?>
    

    This should get you started in the right direction. Regular Expressions won’t account for malformed HTML, and not all Images in your Post HTML are necessarily attachments.

  2. Use this, and replace the $post->ID probably with get_the_ID() if you are inside The Loop.

    <?php //GET THE FIRST IMAGE
        $args = array(
            'order'          => 'ASC',
            'orderby'        => 'menu_order',
            'post_type'      => 'attachment',
            'post_parent'    => $post->ID,
            'post_mime_type' => 'image',
            'post_status'    => null,
            'numberposts'    => 1,
        );
        $attachments = get_posts($args);
        if ($attachments) {
            foreach ($attachments as $attachment) {
                echo wp_get_attachment_link($attachment->ID, 'thumbnail', false, false);
            }
        } 
    ?>
    

    Source: WordPress Support Forums

  3. There’s a very nice plugin called Get The Image. http://wordpress.org/extend/plugins/get-the-image/

    Call by <?php if ( function_exists( 'get_the_image' ) ) get_the_image(); ?>

    The function:

    1) Looks for an image by custom field (one of your choosing).
    2) If no image is added by custom field, check for an image using
       the_post_thumbnail() (WordPress featured image).
    3) If no image is found, it grabs an image attached to your post.
    4) If no image is attached, it can extract an image from your post content
       (off by default).
    5) If no image is found at this point, it will default to an image you set
       (not set by default).