Dynamically add titles to post images if they are empty

You can try the following test plugin, that uses the domDocument class, to see how it works on your HTML.

It assumes PHP 5.4+ with LibXML 2.7.8+.

<?php
/**
 * Plugin Name: Add Missing Image Title Attributes
 * Description: For posts in the main loop (Assumes PHP 5.4+ with LibXML 2.7.8+)
 * Plugin URI:  http://wordpress.stackexchange.com/a/188560/26350
 * Author:      Birgir Erlendsson (birgire)
 * Version:     0.0.1
 */

namespace wpse\birgire;

add_action( 'init', function()
{
    $o = new AddMissingImgTitle;
    $o->activate( new \domDocument );
} );

class AddMissingImgTitle
{
    private $dom;

    public function activate( \domDocument $dom )
    {
        $this->dom = $dom;
        add_filter( 'the_content', [ $this, 'the_content' ] );
    }

    public function the_content( $html )
    {
        if( ! in_the_loop() )
            return $html;

        if( false === strpos( $html, '<img' ) )
            return $html;

        return $this->process( $html );
    }                                                               

    private function process( $html )
    {
        // Handle utf8 strings
        // See http://php.net/manual/en/domdocument.loadhtml.php#95251
        $html="<?xml encoding="UTF-8">" . $html;

        // Load without HTML wrapper
        // See https://stackoverflow.com/a/22490902/2078474
        $this->dom->loadHTML( $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );

        // Fetch all image tags:
        $images = $this->dom->getElementsByTagName( 'img' );
        foreach ( $images as $image )
        {
            // Add the title attribute if it's missing (using the post title):
            if( '' === $image->getAttribute( 'title' ) )
                $image->setAttribute( 'title', esc_attr( get_the_title() ) );
        }
        return str_replace( '<?xml encoding="UTF-8">', '', $this->dom->saveHTML() );
    }

} // end class

For older versions of LibXML, you can check out the answers to this question for alternative ways without the LIBXML_HTML_NOIMPLIED and LIBXML_HTML_NODEFDTD options.

Leave a Comment