Pregunta

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.

¿Fue útil?

Solución

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 );

Otros consejos

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);
Licenciado bajo: CC-BY-SA con atribución
scroll top