Wednesday, April 2, 2014

[php][Solved] Get the first image and display it

Most of the solution from internet are for wordpress and I have edited that for simple php document to use,
You can just copy the code below to a blank php file to test and change the value of $post_content .
<?php
function get_the_post_thumbnail() {
    $post_content = 'asdsadasdasdasdasd<img src="http://s3.buysellads.com/1238343/218873-1397914005.gif">';
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches);
    $first_img = $matches[1][0];
    if(empty($first_img)) {
        $first_img = "/path/to/default.png";
    }
    return $first_img;
}
echo '<img src="'.get_the_post_thumbnail().'"/>';
?>

Result :












Reference:
http://www.wprecipes.com/how-to-get-the-first-image-from-the-post-and-display-it

No comments :

Post a Comment