3

How do I add post title as alt tag in a post? I tried using array(title => '.the_title.') but it didnt work. I think I am not suppose to use the_title. I tired using get_the_title as well.

Thanks

1
  • 1
    Where exactly do you need an alt attribute? Note, there is no alt tag.
    – fuxia
    Jul 10, 2012 at 9:10

3 Answers 3

1

@its_me got it almost right. Those args must be 2nd resp. 3rd Parameter, not first:

$attr = array(
    'title' => 'howdy partner',
    'alt'   => 'a nice view of the ocean',
);

// pick one, note 2 or 3 arguments:
the_post_thumbnail( 'post-thumbnail', $attr );

echo("<a href='$p->permalink'>". // null for current $post->ID (use within loop)
    get_the_post_thumbnail( null, 'post-thumbnail', $attr ).
    "</a>");
0

Try using this <?php the_title(); ?>

Here is example -

<img src="http://link-to-image" title="Image title" alt="<?php the_title(); ?>"/>

1
0

What code does your theme use to show the featured image (aka post-thumbnail)? Most themes do it like this:

<?php the_post_thumbnail(); ?>

or like this (the right way to do it):

<?php 
    if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
        the_post_thumbnail();
    } 
?>

In that case, replace the code with this:

<?php 
    if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
        the_post_thumbnail(
            array(
                'alt' => trim( strip_tags( $attachment->post_title ) ),
            );
        );
    } 
?>

...where, 'alt' => trim( strip_tags( $attachment->post_title ) ) tells the the_post_thumbnail function that it should use the post's title instead of image's alt text.

READ: WordPress Codex — Function Reference for the_post_thumbnail

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.