X
X
xonar2020-04-30 15:24:48
PHP
xonar, 2020-04-30 15:24:48

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>


You can set it manually, of course, but it is necessary that the class be assigned by default.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Vorotnev, 2020-04-30
@xonar

The easiest way is on the hook with a the_contentregular 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 question

Ask a Question

731 491 924 answers to any question