R
R
Roma2016-01-28 14:49:22
WordPress
Roma, 2016-01-28 14:49:22

How to add blocks to images in Wordpress?

Good afternoon) Interested in whether it is possible when adding photos to a page in the 'page editor' to automatically wrap the image in a div?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor Vorotnev, 2016-01-28
@Kavalski

Can. Regular season.

function wrap_images( $content ) {
   $pattern = '/(<img([^>]*)>)/i';
   $replacement = '<div class="myphoto">$1</div>';    
   return preg_replace( $pattern, $replacement, $content );
}
add_filter( 'the_content', 'wrap_images' );

If caption is used, we will need to change the regular expression.

D
Dmitry, 2016-02-04
@dimasmagadan

As Igor suggested, it can be done in some cases (for example, if you need to correct the output of pictures already existing in the content).
But it would be more correct to correct the output of old images in the database once and then attach to image_send_to_editor
https://developer.wordpress.org/reference/hooks/im...
This way you won’t need a regular expression, you can more flexibly configure the output depending on the availability caption, image size, alt and more.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question