I want to figure out how to add an alt attribute to pre-existing images on the site. I've read all the other posts I can find on StackOverflow and Wordpress.org, tested multiple functions, and haven't had much luck. Any help would be greatly appreciated.
In my functions.php file, this function exists, but it doesn't appear to do anything.
/* add alt attributes to all images */
function isa_add_img_title( $attr, $attachment = null ) {
$img_title = trim( strip_tags( $attachment->post_title ) );
$attr['title'] = $img_title;
$attr['alt'] = $img_title;
return $attr;
}
add_filter( 'wp_get_attachment_image_attributes','isa_add_img_title', 10, 2 );
Here is a previous function I've also implemented with no effect.
function addImageAlt($attribute){
$imgAttribute = trim( strip_tags($attribute->post_title) );
$totalAttribute["alt"] = $imgAttribute;
return $totalAttribute;
}
add_filter("wp_get_attachment_image", "addImageAlt", 10, 5);
Here is the template code, which is getting the image source
{
extract($atts);
if (!is_front_page()):
wp_enqueue_script('slick', get_template_directory_uri() . '/assets/js/slick.min.js', array( 'jquery' ), '20160816', true);
wp_enqueue_style('slick-css', get_template_directory_uri() . '/assets/css/slick.css');
endif;
$html = '<div class="brands-slider-wrapper">
<div class="brands-slider">';
$loop = new WP_Query(array( 'post_type' => 'zm_brands', 'posts_per_page' => $num_of_brands, 'order' => 'ASC', 'orderby' => 'meta_value' ));
if ($loop && $loop->post_count > 0) :
while ($loop->have_posts()) : $loop->the_post();
$imgsrc=wp_get_attachment_image_src(get_post_thumbnail_id(), 'brand-thumb');
$brand_thumbnail= $imgsrc[0] != "" ? $imgsrc[0] : get_template_directory_uri() . '/assets/images/default-music-icon.jpg';
$html.='<div class="slide-brand">
<div class="brand-logo-thumbnail">
<a href="'.get_permalink().'">
<img src='.$brand_thumbnail.' alt="'.basename($brand_thumbnail).'" title="'.get_the_title().'">
</a>
</div>
</div>';
endwhile;
endif;
$html .='</div>
</div>';
wp_reset_query();
return $html;
}
The images for the sliders on the website appear to be sourced differently.
$html .= '<div class="slide-instrument">
<div class="instrument-category-thumbnail auto-height">
<img src=' . $category_thumbnail . '" alt="' . $term->slug . '" title="' . $term->name . '">
</div>
<h4>' . $term->name . '</h4>
<a href="' . get_term_link($term->slug, $taxonomy) . '"><span>View More</span></a>
</div>';
I figured this out by instead editing the application.js file, and adding this jquery function
$('img').attr('alt', function(){
var src = this.src.split('/').pop().split('.')[0];
return src;
});
This simply adds alt attributes to all images on the site, and is not necessarily the best way to do so, but it worked for me.