How to Automatically Wrap Images in the_content with Custom HTML in WordPress

Home » Snippets » How to Automatically Wrap Images in the_content with Custom HTML in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you looking for a way to add custom HTML around images in your WordPress post content? By default, WordPress doesn’t provide a built-in option to automatically wrap images with custom HTML when using the_content function. However, with a few lines of code, you can easily achieve this customization. In this article, we will explore how to automatically wrap images in the_content with your own custom HTML.

					function wpturbo_wrap_images($content) {
    $pattern = '/<img(.*?)src="(.*?)"(.*?)>/i';
    $replacement = '<div class="wpturbo-image-wrapper"><img$1src="$2"$3></div>';
    $content = preg_replace($pattern, $replacement, $content);
    return $content;
}
add_filter('the_content', 'wpturbo_wrap_images');
				

In this code snippet, we are creating a function called wpturbo_wrap_images that will automatically wrap images in the content of a WordPress post or page with custom HTML.

First, we set a regular expression pattern using the $pattern variable. This pattern searches for <img> tags with their attributes and captures three groups: $1, $2, and $3.

The first group $1 captures any additional attributes that might be present in the <img> tag. The second group $2 captures the image source URL. The third group $3 captures any additional attributes after the src attribute.

Next, we define the HTML replacement using the $replacement variable. Here, we wrap the captured <img> tag within a <div> element with a class of "wpturbo-image-wrapper". This will serve as the custom HTML wrapper for the images.

Now, we use the preg_replace() function to perform a regular expression search and replace operation. We pass in the $pattern, $replacement, and the $content as the third argument. The preg_replace() function will search for any occurrences of the $pattern in the $content and replace them with the $replacement.

Finally, we return the modified $content from the function.

To make sure that this function is applied to the content of every post or page, we use the add_filter() function. We hook the wpturbo_wrap_images function to the the_content filter. Whenever the the_content filter is applied, our wpturbo_wrap_images function will be executed, automatically wrapping any images with our custom HTML.

This allows you to easily customize the appearance or behavior of images within the content of your WordPress website.

Register an account to save your snippets or go Pro to get more features.