Loading Symbol

How to Remove Attributes from WordPress Thumbnail HTML

Crystal Ball Featured Image

This article will show you how to remove attributes from the featured image HTML output of get_the_post_thumbnail() with preg_replace(). Sometimes you need the post featured image or thumbnail but not all the attributes that WordPress adds to it. Fortunately, there is a simple regular expression to strip any attributes you don’t need. You can use it globally with a hook or in a one-off instance in a page template. The example below will strip the width, height, class, srcset and sizes attributes.

Loading GIF

<?php
$thumbnail  = get_the_post_thumbnail($post->ID);

echo $thumbnail; // <img width="233" height="333" src="/wp-content/uploads/2019/01/image.png" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="Image Alt Text" srcset="/wp-content/uploads/2019/01/image.png 233w, /wp-content/uploads/2019/01/image-210x300.png 210w" sizes="(max-width: 639px) 98vw, (max-width: 1199px) 64vw, 233px">

// Add whichever attributes you want to exclude here
$thumbnail = preg_replace( '/(width|height|class|srcset|sizes)="[^"]*"/', '', $thumbnail );

echo $thumbnail; // <img src="/wp-content/uploads/2019/01/image.jpg" alt="Image Alt Text">

How It Works

First, we get the post thumbnail as an HTML image tag with get_the_post_thumbnail(). Then we use a regular expression that matches the attributes we want to remove. The regular expression matches each attribute followed by any attribute value (any number of characters except the double quote character). The matches are replaced with the empty string. That’s it!


Loading Symbol


Leave a Reply

Your email address will not be published. Required fields are marked *