-
-
Save jcamp/3daffa66133db38cbe1bf26bc1e08b59 to your computer and use it in GitHub Desktop.
Wordpress Get first image in post content if no featured image is available. (blog)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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