Dynamically add titles to post images if they are empty

I have a client’s site where they want to add image title attributes dynamically to images that don’t have one already. So if the title attribute is empty, add a title of whatever the post title is. How would I accomplish this?

<img src=img.jpg title=[wp-post-title-here] />

Solutions Collecting From Web of "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+.

 * 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.

If we can assume that this is done properly for images that are in templates, and you’re only concerned about page/post body content, you could use a filter when saving any post or page ( https://codex.wordpress.org/Plugin_API/Action_Reference/save_post ) to scan the content

Since this action is triggered right after the post has been saved,
you can easily access this post object by using get_post($post_id)

You should then be able to do a search for all image tags <img, and if they do not have the phrase title=" before the next >, insert right after <img your title="post title here" – don’t forget to re “save” the post after the whole function runs.

In order to do that, I would split the post string into substrings and then reassemble them again, but it’s out of scope here to write all the code for you.

Alternatively you could do a similar scan for the image tags when the code is displayed to the page by filtering on get_content or similar, but it makes more sense to save into the database correctly, in regard to page load for viewers.

Does the image title attribute actually have to be in the database? If it’s only the matter of displaying text, for example in the photo gallery, would’t using a jQuery function serve your purpose? Something like:

$(document).ready(function() {
  $('img').each(function() {
    if ($(this).attr('title') === undefined) {
         var title = $('h1').text();
         $(this).attr('title', title);

It means that you want to load that image on post right…
place the below code where you want images

$post_id = 75;
$thumbnail_id = 112;
    echo '<img src="img.jpg" title="'.get_the_title($thumbnail_id).'" />';
    echo '<img src="img.jpg" title="'.get_the_title($post_id).'" />';


i hope it will work for you…