Wordpress - changing attributes of featured images

2.1k Views Asked by At

I want to use Featured Images (thumbnails) in my posts.

The thing is, I want to be able to change the following image attributes after the image has been attached to the post, but before the post has been published:

Title Alternate Text Caption Description

How do you do that?

3

There are 3 best solutions below

2
On
<?php 

$size = array(150,150);

$default_attr = array(
            'src'   => $src,
            'class' => "attachment-$size",
            'alt'   => trim(strip_tags( wp_postmeta->_wp_attachment_image_alt )),
            'title' => trim(strip_tags( $attachment->post_title )),
        );

the_post_thumbnail( $size, $attr ); 

?> 
0
On

I'm still not clear what you're trying to do.

This will display the featured image in your markup using the post title as alt and title attributes.

$image_meta = wp_get_attachment_image_src( get_post_thumbnail_id(), 'medium'); 
// replace 'medium' with 'thumbnail', 'large', or 'full'.
echo '<img src="'.$image_meta[0].'" alt="'.$post->post_title.'" title="'.$post->post_title.'" width="'.$image_meta[1].'" height="'.$image_meta[2].'"/>';

If you want to actually change the featured image title, alt, caption, description etc in the database, then you could look at the post_publish hook. This should get you started:

function do_stuff($post_ID){
    global $post;
    $post_thumbnail_id = get_post_thumbnail_id($post_ID);
    if ($post_thumbnail_id){
        // Do Stuff with your featured image id - $post_thumbnail_id
    }
return $post_ID;
}
add_action('publish_post', 'do_stuff');
0
On

try this and its work fine.

$title_attribute = the_title_attribute( array( 'echo' => FALSE ) );
the_post_thumbnail(
    'full', 
     array(
        'alt'   => $title_attribute, 
        'title' => $title_attribute 
    )
);