Answer the question
In order to leave comments, you need to log in
How to classify images inside a WordPress post?
Good day everyone.
Suggest a solution to the problem. How to set a class for all images that are inside a post?
It is necessary to set the img class.
<figure class="wp-block-image size-large">
<img src="https://66.media.tumblr.com/e852a06b7e1fbf228dc52b996720c0b3/tumblr_pw9s3vrBoG1utlor0o1_1280.jpg" alt="" class="">
</figure>
Answer the question
In order to leave comments, you need to log in
The easiest way is on the hook with a the_content
regular replacement or a regular expression, but this is if the pictures always have the same structure (for example, we know exactly what the tag will be <img src="..." class="..." ...
). But in general, parsing html with regular expressions is not the brightest idea - there is a DOMDocument for this:
function add_class_to_images( $content )
{
$document = new DOMDocument();
libxml_use_internal_errors(true); // чтобы не ругался на семантические HTML5 теги
$document->loadHTML( $content );
libxml_clear_errors();
$images = $document->getElementsByTagName( 'img' );
/** @var \DOMElement $image */
foreach ( $images as $image ) {
$image->setAttribute(
'class',
$image->getAttribute( 'class' ) . ' my-new-class'
);
}
return $document->saveHTML();
}
add_filter( 'the_content', 'add_class_to_images' );
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question