Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save brajeshwar/1205901 to your computer and use it in GitHub Desktop.
Save brajeshwar/1205901 to your computer and use it in GitHub Desktop.
Wordpress - Get the Image from Post Thumbnail or the First Image of a post or else use a default Image.
/*
* Display Image from the_post_thumbnail or the first image of a post else display a default Image
* Chose the size from "thumbnail", "medium", "large", "full" or your own defined size using filters.
* USAGE: <?php echo my_image_display(); ?>
*/
function my_image_display($size = 'full') {
if (has_post_thumbnail()) {
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id, $size);
$image_url = $image_url[0];
} else {
global $post, $posts;
$image_url = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$image_url = $matches [1] [0];
//Defines a default image
if(empty($image_url)){
$image_url = get_bloginfo('template_url') . "/img/default.jpg";
}
}
return $image_url;
}
@pohau1991
Copy link

before the last if statement, if first_img is empty then you could just do preg_match_all('/[img].+'"['"].*[/\img]/', $post->post_content, $matches2);)
$first_img = $matches2[1][0]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment