clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Get the first image inserted into a post body in WordPress

Filed under: WordPress/PHP— Tagged with: functions.php, snippets

Sometimes It’s nice to show to the first image in the post archive page.

This is a very simple script, does one thing. Just paste this in your themes functions.php file:

function get_first_inserted_image() {
  global $post, $posts;
  preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];
  // Spew it out as an imege
  $first_img = '<img alt="Blog Post Image" src="' . $first_img . '">';
  return $first_img;
}

Use it like this:

echo get_first_inserted_image();

Source

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!