Search code examples
phphtmlwordpressseo

Dynamically change image titles and alt tags through PHP - On html render, not in database


I want to re-title my image's alt tags etc based on the page they are being displayed on. For SEO Purposes.

I've tried to write a PHP function to do so and call the function on page load with "alt=<?php echo $post_title ?>" and "title=<?php echo $post_title ?>" but nothing is working.

How would you do it? PHP or jQuery... or?

Here's one of the functions I tried to manipulate and turn into something that works... I did get it to change the alt tags but I havent had any success beyond that.

function isa_add_img_title( $attr, $attachment = null ) {

    $img_title = trim( strip_tags( $attachment->post_title ) );

    $attr['title'] = $img_title;
    $attr['alt'] = $img_title;

    return $attr;
}
add_filter('wp_get_attachment_image_attributes','isa_add_img_title', 10, 2);

It appears this post may have had the answer but the link in the answer is now broken: Dynamically filling image alt tags with the page title, PHP

Thanks so much! Appreciate any help.


Solution

  • This will set the alt and title of every image on the page to the post title.

    function duck_diver_add_img_title( $attr, $attachment = null ) {
        // Fetch the global post object. This is what the page it's on is.
        global $post;
        // Get the post title.
        $img_title = wp_kses_post( $post->post_title );
    
        $attr['title'] = $img_title;
        $attr['alt']   = $img_title;
    
        return $attr;
    }
    add_filter( 'wp_get_attachment_image_attributes', 'duck_diver_add_img_title', 10, 2 );