To display the first image from the post content use the following function given.
First open your active theme's functions.php file in a code editor. After opening the file in the code editor add the following function at the end of the file.
The function can be called in the loop or anywhere to display the first image from the post.
First open your active theme's functions.php file in a code editor. After opening the file in the code editor add the following function at the end of the file.
<?php
function get_first_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
?>
Save the file and upload it back to the server.The function can be called in the loop or anywhere to display the first image from the post.
<?php echo catch_that_image() ?>
No comments:
Post a Comment