Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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 = '';
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$image_url = $matches [1] [0];
//Defines a default image
$image_url = get_bloginfo('template_url') . "/img/default.jpg";
return $image_url;

This comment has been minimized.

Copy link

@lonchbox lonchbox commented Aug 12, 2015

Could you please show an example of how to apply new image sizes filters ?
Also, after testing it doesn´t work if the post have more than one image :(


This comment has been minimized.

Copy link

@dan74mm dan74mm commented May 26, 2016

Need some help ...
My blog posts/articles, have [img]image-URL[/img] shorcode created in functions.php theme file.

In my blog posts, I use images with this [img] shortcode, something like this:

How to make this "first-image" function to get first image from [img]xxx[/img] tag, if I don't have usual <img src="" /> in my blog post?

This is my code:

function catch_first_image() {
  global $post, $posts;
  $first_img = '';
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  if(empty($first_img)){ //Defines a default image
    $first_img = "/images/default.jpg";
  return $first_img;

Thank you.


This comment has been minimized.

Copy link

@pohau1991 pohau1991 commented May 3, 2017

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