Skip to content

Instantly share code, notes, and snippets.

@rafiul
Last active July 13, 2019 16:17
Show Gist options
  • Save rafiul/717e0cf3b6054f1ee0dad26a1e43c6fa to your computer and use it in GitHub Desktop.
Save rafiul/717e0cf3b6054f1ee0dad26a1e43c6fa to your computer and use it in GitHub Desktop.
Get WordPress first image of posts if featured image not provided.
//=======Function of get first image of posts ========
function get_first_image_of_posts() {
global $post;
$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)) {
$first_img = "/path/to/default.png";
}
return $first_img;
}
//====== Usage ========
if ( get_the_post_thumbnail() != '' ) {
the_post_thumbnail();
}else{
<img src="<?php echo get_first_image_of_posts();?>" alt="">
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment