Grabbing the URL of the First Image From a Post

If you are familiar with the Open Graph Protocol then you must have known already that it is important to provide an image url with every blog post you write. This enables your blog post to be a rich object over a regular blog post that doesn’t follow the Open Graph Protocol.

Today in this post I will show you how to grab the url of the first image of your blog post and use it for various purpose. You can even use this code instead of typical thumbnail functionality in WordPress. This code could be also very useful if you want to implement Twitter Summary Card for your website.

Let’s take a look at the actual code.

<?php
function first_image_url() {
   global $post, $posts;
   $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)){ //Defines a default image
   $first_img = "https://www.urdomain.com/default-image.jpg"; }
   return $first_img; }
?>

Simply copy and paste the above snippet on your theme’s functions.php file and update it. Now see carefully, at the end of the code I also provided a default URL of an image which would be useful if we don’t have any image within the post. You can change it with your own default post image url.

You can call this function within <img> tag to display image from your post.

<img src="<?php echo first_image_url(); ?>">

Or you can call this function within the Open Graph meta tag. See the example below.

<meta property="og:image" content="<?php echo first_image_url(); ?>">

That’s pretty much it. Feel free to share this post if you find it to be useful.

Today In History

  •  
  •  

Comment

Leave a Reply

Note: Convet HTML, PHP, JavaScripts from Postable, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.