• Resolved Scofield

    (@scofield)


    Hello, I have a question. How can I change thumbnail title and alt in my theme?

    Now I have in index.php
    <?php the_post_thumbnail(array(150,150)); ?>
    and in functions.php

    add_theme_support('post-thumbnails');
    add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 3 );
    
    function my_post_image_html( $html, $post_id, $post_image_id ) {
    
    	$html = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( get_post_field( 'post_title', $post_id ) ) . '">' . $html . '</a>';
    
    	return $html;
    }

    Thanks for reply ??

Viewing 10 replies - 1 through 10 (of 10 total)
  • Thread Starter Scofield

    (@scofield)

    Nobody knows? ??

    I am also trying to find where to get the thumbnail title and also the caption text.

    Stop looking further guys. It’s not possible.

    You can do this using regular expressions. I have not tested the second example, but the first is practically pasted from a blog that I have been working on.

    add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 3 );
    function my_post_image_html( $html, $post_id, $post_image_id ) {
    	// Example: Use post title instead of image title.
    	$post_title = esc_attr( get_post_field( 'post_title', $post_id ) );
    	// Replace image title with post title.
    	$html = preg_replace( '/(<img[^>]*title\s*=\s*)"[^"]*"|\'[^\']*\'/', '$1"'.$post_title.'"', $html, 1 );
    
    	// Example: Use "Post Thumbnail" for "alt".
    	$html = preg_replace( '/(<img[^>]*alt\s*=\s*)"[^"]*"|\'[^\']*\'/', '$1"Post Thumbnail"', $html, 1 );
    
    	return $html;
    }

    I hope that this is of use.

    There is another way too:
    Change the attributes of thePostThumbnail in the template (index,page,..)
    for the alt use array alt

    thePostThumbnail(array('alt' => ''.get_the_title().''));

    for the title use array title

    thePostThumbnail(array('title' => ''.getTheTitle().''));

    no need to change stuff in the functions.php

    You can add lots of parameters, for example:

    the_post_thumbnail( 'thumbnail', array('class' => 'alignleft post_thumbnail', 'style' => 'width: 186px;', 'alt' => 'no alt', 'title' => ''.get_the_title().'' ));

    Thanks walterdevos! That is really useful to know!

    Thanks, I needed this as well

    @walterdevos: thanks a lot!

    @walterdevos
    Ahh! this has been driving me nuts. Thanks for the solution!

    anthonymasure

    (@anthonymasure)

    Thank you very much walterdevos !

Viewing 10 replies - 1 through 10 (of 10 total)
  • The topic ‘Thumbnail title and alt?’ is closed to new replies.