Skip to content

Instantly share code, notes, and snippets.

@barbwiredmedia
Last active July 6, 2018 18:00
Show Gist options
  • Save barbwiredmedia/e9bc36ff16185d27eee2 to your computer and use it in GitHub Desktop.
Save barbwiredmedia/e9bc36ff16185d27eee2 to your computer and use it in GitHub Desktop.
Wordpress Get first image in post content if no featured image is available. (blog)
// Get First image for Blog section
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 = "";
if (isset($matches[1][0]))
$first_img = $matches[1][0];
return $first_img;
}
<?php $postimg = get_first_image(); ?>
<?php
if (has_post_thumbnail()):
the_post_thumbnail();
elseif ($postimg):
?>
<img src="<?php echo $postimg; ?>"/>
<?php else: ?> <img src="DEFAULT IMG SRC HERE" alt=""/>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment