Add Snippet To Project
Are you looking to display the first image of a post on your WordPress website? Displaying the first image can help draw attention to your content and make it more visually appealing. In this article, we’ll show you how to easily retrieve and display the first image of a post using WordPress functions and techniques. Whether you’re a beginner or an experienced WordPress developer, this guide will help you achieve your desired result. Let’s dive in!
function wpturbo_get_first_image_in_post() {
global $post;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
return $first_img;
}
The wpturbo_get_first_image_in_post() function is designed to retrieve the first image in a WordPress post. This can be useful for a variety of purposes, such as creating image galleries or displaying a featured image.
Let’s break down how this function works.
First, we start by declaring a global variable $post. This variable represents the current post, and is necessary in order to access the post’s content.
Next, we initialize the variable $first_img as an empty string. This variable will store the URL of the first image found in the post.
Then, we call ob_start() to start output buffering, and ob_end_clean() to discard the buffer without displaying it. This is done to prevent any unwanted content from being displayed.
The preg_match_all() function is then used to perform a regular expression search on the post content. This allows us to search for all occurrences of an <img> tag and extract the source URL of the image.
The regular expression used is /<img.+src=['"]([^'"]+)['"].*>/i.
<img.+matches the opening<img>tag and any additional attributes.src=['"]([^'"]+)['"]captures the source URL of the image within single or double quotes..*>matches the remaining contents of the image tag, including any closing>.
The results of the regular expression search are stored in the $matches variable. The URL of the first image found is then extracted from the sub-array $matches[1][0] and assigned to the $first_img variable.
Finally, the function returns the URL of the first image.
To use this function, you can simply call wpturbo_get_first_image_in_post() wherever you need to retrieve the first image in a post.
