3

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?

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

7
  • Could you elaborate what you mean by "add" precisely? Adjust markup inserted into post content? Something else?
    – Rarst
    May 8, 2015 at 21:38
  • It is supposed to add the title attribute to an 'img' element @Rarst May 8, 2015 at 23:07
  • @ZachRussell When should it do it? Should the title be added during saving given post or should it work also for old/existing posts? May 13, 2015 at 19:27
  • @KrzysiekDróżdż It should work for old/existing posts and new posts. May 13, 2015 at 21:01
  • How are you displaying the image on the page? the_post_thumbnail, wp_get_attachment_image, hard coding <img src="<?php echo $src; ?>" />, a gallery plugin, or some variant?
    – DACrosby
    May 13, 2015 at 21:30

4 Answers 4

2
+50

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.

1

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.

0

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);
      }
  });
});
1
  • I'm not looking for a jQuery solution. Thank you for your answer though. May 13, 2015 at 21:03
0

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

<?php
$post_id = 75;
$thumbnail_id = 112;
if(!empty(get_the_title($thumbnail_id))){
    echo '<img src="img.jpg" title="'.get_the_title($thumbnail_id).'" />';
}
else{
    echo '<img src="img.jpg" title="'.get_the_title($post_id).'" />';
}

?> 

i hope it will work for you...

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.