Monday, April 16th, 2018
Function for grabbing image from post and using it instead of a featured image for example.
Add this to functions.php
// Get URL of first image in a post
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$matches[1][0] = '';
if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)){
$first_img = $matches[1][0];
}
// no image found display default image instead
return $first_img;
}
And call in the theme with
<img src="<?php echo catch_that_image() ?>" onerror="this.style.display = 'none';"/>
Tags: catch that image, featured image, first image, first image from post, Functions, PHP, wordperss
Posted in PHP, WordPress | No Comments »