Ben Darlington
Ben Darlington

Reputation: 161

Add image alt to WP Post Thumbnails

I am trying to add the alt attribute to post thumbnails on my blog.

I get the alt text to echo, but not as an attribute, but as text!

  <?php if ( has_post_thumbnail() ) {$image_src = wp_get_attachment_image_src( get_post_thumbnail_id(),’thumbnail’ ); $image_alt = wpseoFocusKW();
    echo '<img width="100%" src="' . $image_src[0] . '" alt=' . $image_alt .' >';} ?></div></div> 

You can see the issue here: http://benefacto.org/three-days-paid-volunteering-leave-an-update-from-rob-wilsons-office/

You will note I'm using the Yoast Keyword as the alt, which works fine.

Any thoughts much appreciated.

Ben

Upvotes: 0

Views: 708

Answers (1)

Sebastian Brosch
Sebastian Brosch

Reputation: 43564

Try the following (only PHP part):

<?php 
    if (has_post_thumbnail()) {
        $image_src = wp_get_attachment_image_src(get_post_thumbnail_id(),'thumbnail'); 
        $image_alt = wpseo_get_value('focuskw', $post->ID);
        echo '<img width="100%" src="'.$image_src[0].'" alt="'.$image_alt.'">';
    } 
?>

The content of the function wpseoFocusKW() looks like this:

function wpseoFocusKW()
{
    $focuskw = wpseo_get_value('focuskw', $post->ID);
    echo $focuskw;
}

This function only echo the keyword, but don't return!
Reference: http://snipplr.com/view/67931/

You can create a custom function or change the original like this:

function wpCustomSeoFocusKW($return = false)
{
    $focuskw = wpseo_get_value('focuskw', $post->ID);

    if ($return) {
        return $focuskw;
    } else {
        echo $focuskw;
    }
}

Upvotes: 1

Related Questions