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— 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. Tweet me @hiljaa if you want to make a correction etc.

  • © 2021 Antti Hiljá
  • About
  • Follow me in Twatter → @hiljaa
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!