How to modify an image block in Gutenberg WordPress 5?

Question

Adding images to a post with the block editor:

enter image description here

produces the code figure of:

<figure class="wp-block-image">
    <img src="http://localhost:8888/time.png" alt="alt text" class="wp-image-1391"/>
    <figcaption>This is an image test.</figcaption>
</figure>

but I’m using Bootstrap 4 and would like to add Spacing (such as mt-2) and to remove the image class wp-image-1391, result:

<figure class="mt-2">
    <img src="http://localhost:8888/time.png" alt="alt text" class="img-fluid"/>
    <figcaption>This is an image test.</figcaption>
</figure>

or be able to modify it to a div:

<div class="mt-2">
    <img src="http://localhost:8888/time.png" alt="alt text" class="img-fluid"/>
    <figcaption>This is an image test.</figcaption>
</div>

Researching I’ve found get_image_tag_class but testing:

function example_add_img_class($class) {
    return $class . ' img-fluid';    
}
add_filter('get_image_tag_class','example_add_img_class');

doesn’t work. Reading “How can I prevent WordPress from adding extra classes to element in the WYSIWYG editor” I tested:

add_filter('get_image_tag_class','__return_empty_string');

but doesn’t work. I can modify the <img> with a preg_replace using the_content add_filter:

function add_image_fluid_class($content) {
    global $post;
    $pattern        = "/<img(.*?)class="(.*?)"(.*?)>/i";
    $replacement    = '<img$1class="$2 img-fluid"$3>';
    $content        = preg_replace($pattern,$replacement,$content);
    return $content;
 }
 add_filter('the_content','add_image_fluid_class');

function img_responsive($content){
    return str_replace('<img class="','<img class="img-responsive ',$content);
}
add_filter('the_content','img_responsive');

but I’ve read that targeting the_content with regex can yield mixed results. I could solve the issue with a simple CSS:

figure img {
    width:100%;
    height:auto;
}
figure figcaption {
    text-align:center;
    font-size:80%;
}

but I’d like to understand more of what filters I can use to modify WordPress. How can I add and remove classes and change figure to a div?

0
, , , DV 4 years 2019-01-17T21:02:32-05:00 0 Answers 161 views -1

Leave an answer

Browse
Browse