4

The default behavior when it comes to full-width images in posts is this:

  • If you insert an image alone, this HTML structure is produced: <p><img/></p>
  • If you insert an image with a caption, the HTML structure is produced: <figure><img/><figcaption/></figure>

For the sake of styling (I want to have larger margin around images compared to standard paragraphs), I'd like to get <figure> in both cases, not just when there is a caption. How to do it?

Edit: one thing I noticed is that the behavior changes as soon as Visual and Text tabs are switched in the editor, i.e., even before previewing or saving the post. Maybe the correct solution would be to somehow force WordPress editor to always use the [caption] shortcode no matter what.

7

You can try the image_send_to_editor filter:

/**
 * Wrap the inserted image html with <figure> 
 * if the theme supports html5 and the current image has no caption:
 */

add_filter( 'image_send_to_editor', 
    function( $html, $id, $caption, $title, $align, $url, $size, $alt ) 
    {
        if( current_theme_supports( 'html5' )  && ! $caption )
            $html = sprintf( '<figure>%s</figure>', $html ); // Modify to your needs!

        return $html;
    }
, 10, 8 );

where you can modify the html of the image when it's inserted into the editor.

I added the check for current_theme_supports( 'html5' ) in the above filter, to check if you have something like:

add_theme_support( 'html5', array( ... ) );

in your theme. But you might not want to have this filter callback dependent on your current theme, so you can remove it if you want.

You could also try out the get_image_tag filter.

Update: Here's the useful unautop function from @bueltge's comment (for better readability):

// unautop for images     
function fb_unautop_4_img( $content )
{ 
    $content = preg_replace( 
        '/<p>\\s*?(<a rel=\"attachment.*?><img.*?><\\/a>|<img.*?>)?\\s*<\\/p>/s', 
        '<figure>$1</figure>', 
        $content 
    ); 
    return $content; 
} 
add_filter( 'the_content', 'fb_unautop_4_img', 99 );
  • That is a great answer. Just a follow up question - adding this image_send_to_editor will affect the new posts only, right? If I wanted to also retro-fix the markup in all the historic blog posts, I would probably need to filter the whole post content and find the <p><img.../></p> pattern and replace it with figure, right? – Borek Bernard Jan 12 '15 at 10:50
  • 2
    If you will use this also for old Posts, then use the filter of content. But as hint, this a performance break. This source filter the content and change the images in the figure tag. // unautop for images function fb_unautop_4_img( $content ) { $content = preg_replace( '/<p>\\s*?(<a rel=\"attachment.*?><img.*?><\\/a>|<img.*?>)?\\s*<\\/p>/s', '<figure>$1</figure>', $content ); return $content; } add_filter( 'the_content', 'fb_unautop_4_img', 99 ); – bueltge Jan 12 '15 at 21:34
  • 1
    Sure, I just added it to the answer. Feel free to edit it if needed @bueltge – birgire Jan 13 '15 at 9:12
  • 1
    image_send_to_editor works perfectly, thanks. Also a big thanks to @bueltge for the content filter. – Borek Bernard Jan 13 '15 at 14:59
  • 1
    Very nice - thanks! I decided to use check for ! strstr( $html, '<figure' ) instead of ! $caption in case they fix this in a future version of wordpress. – squarecandy May 18 '17 at 23:03
2

I know this is an old question with an accepted answer, but I used the the_content version of this answer and in some circumstances it actually fails and wraps more than the image in a figure.

I guess this is the reason one shouldn't parse code using regular expressions.

So... I came up with another solution using DOMDocument. It's nowhere near as short as the regexp one but it feel stable:

<?php
add_filter('the_content', function ($content) {
    # Prevent errors so we can parse HTML5
    libxml_use_internal_errors(true); # https://stackoverflow.com/questions/9149180/domdocumentloadhtml-error

    # Load the content
    $dom = new DOMDocument();

    # With UTF-8 support
    # https://stackoverflow.com/questions/8218230/php-domdocument-loadhtml-not-encoding-utf-8-correctly
    $dom->loadHTML('<?xml encoding="utf-8" ?>' . $content);

    # Find all images
    $images = $dom->getElementsByTagName('img');

    # Go through all the images
    foreach ($images as $image) {
        $child = $image; # Store the child element
        $wrapper = $image->parentNode; # And the wrapping element

        # If the image is linked
        if ($wrapper->tagName == 'a') {
            $child = $wrapper; # Store the link as the child
            $wrapper = $wrapper->parentNode; # And its parent as the wrapper
        }

        # If the parent is a <p> - replace it with a <figure>
        if ($wrapper->tagName == 'p') {
            $figure = $dom->createElement('figure');

            $figure->setAttribute('class', $image->getAttribute('class')); # Give figure same class as img
            $image->setAttribute('class', ''); # Remove img class
            $figure->appendChild($child); # Add img to figure
            $wrapper->parentNode->replaceChild($figure, $wrapper); # Replace <p> with <figure>
        }
    }

    # Turn on errors again...
    libxml_use_internal_errors(false);

    # Strip DOCTYPE etc from output
    return str_replace(['<body>', '</body>'], '', $dom->saveHTML($dom->getElementsByTagName('body')->item(0)));
}, 99);
  • Do you understand you can be significantly delaying the time it takes to serve the content by doing this? – Dylan Maxey Jun 15 at 17:24
  • Why? Running this code takes basically no time at all. – powerbuoy Jun 15 at 17:30
  • Maybe not on a small or test website. But if you're running this code by many users at the same time it will bog down the load time, hindering the performance of the site by at least hundreds of milliseconds. – Dylan Maxey Jun 15 at 18:53
  • IMO, I'd say one would be better off running code 'similar' to this via wp_schedule_event and run it on all of the posts' content in the database. – Dylan Maxey Jun 15 at 18:57
  • This is one example stating the inferior performance of DOMDocument, but there are many others and I wouldn't suggest this for a production website blog.futtta.be/2014/05/01/… – Dylan Maxey Jun 15 at 19:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.