Last active
July 13, 2019 16:17
-
-
Save rafiul/717e0cf3b6054f1ee0dad26a1e43c6fa to your computer and use it in GitHub Desktop.
Get WordPress first image of posts if featured image not provided.
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
//=======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