How to Get The First Image From a WordPress Post?

In this tutorial, you will learn how to get the first image from a WordPress post and use it as you want like as a featured image, as a hero image, as a banner image, etc.

Let’s say you have a very old WordPress blog and you haven’t uploaded the featured image for them and now you want to upload the feature image for them. But if you do one by one post it will be very time-consuming, you know that.

So here is the case of this tutorial, where you probably know that the post content has at least one image and you want that image as a featured image of the post. So let’s do that in very simple code.

We will use the preg match function to find the all images from post content and get the only first image by specifying the index number 0.

You can also assign the default image to the post if there is no image found in the post content. That default image you can use as per your need on the frontend side.

Let’s see how you can get the first image from post content.

Get First Image of WordPress Post

To get the first image from WordPress post content, we have to first make a function and then write down the expression match in the preg_match_all() function.

Then we will check if the images are found and return the first image by 0 indexing otherwise return the default image to show. Let’s see the code below.

Add this function to your child theme‘s functions.php file and now you can use it in any action hook to get the first image from WordPress post content.

You can also directly use this function in a single.php file to show the image for the WordPress post on the front end side.

If you want to use an archive posts loop, you just have to make the condition to check first the post has thumbnail or not using the has_post_thumbnail() function and then print it. See the below code.

So in the above code, we checked whether the post has a featured image or not, if not then make the first image of the post as a featured image.

As I said above you can use it as you want to make a hero image, banner image, featured image, etc, and style it as per your theme design.

Hope you like it. If you have any queries do let me know in the comment section, and I will respond to you as soon as possible.

Leave a Comment