Abhik Abhik - 2 months ago 21
jQuery Question

Change/Add Image Title and Alt within a WordPress Post

I am trying to replace alt and title properties of all the images present in a WordPress post/page using jQuery with the post title.

I tried several codes, but nothing is working can you please help me on this?

Here is one of code I tried. Looks like it should work, but it isn't.

<?php function ia_prop_js() {
global $post; ?>
<script type="text/javascript">
$(document).ready(function() {
$( ".hentry" ).find("img").each(function() {
$(this).attr("title", "<?php echo esc_attr(get_the_title($post->ID)); ?>");
$(this).attr("alt", "<?php echo esc_attr(get_the_title($post->ID)); ?>");
});
});
</script>
<?php }
add_action('wp_head', 'ia_prop_js');
?>

Answer

On your test url if I this on the console

jQuery( ".hentry" ).find("img").each(function() {
       jQuery(this).attr("title", "new");
       jQuery(this).attr("alt", "new");
});

it changes title and alt. So either it is the $ or your get_the_title does not return a title (maybe is outside the loop)

Comments