Trying to add an img class = "the image alt field" to the images in a native wordpress gallery so i can use jquery isotope to filter the gallery. I could use the image alt field or the description field to give the image a simple class of "apple" or "orange" or "apple tasty". This should probably be done using tags somehow but surprising that is not a feature of wordpress.

add_filter('wp_get_attachment_link', 'galleryWIthClass');

function galleryWithClass($src) {

global $post;
$alt= get_post_meta($id, '_wp_attachment_image_alt', true);

echo str_replace('<img', '<img class="'. $alt.'" ', $src);


This code results in : img class = "".

I need to set $id = "something" in order to return some sort of value.

I feel im approaching this wrong.

Any advice?

  • Perhaps wp_get_attachment_image_attributes would be a more appropriate filter. – t31os Apr 22 '13 at 7:37

try this.Passed $attachment->ID to get_post_meta to retrive alt tag of each image

add_filter('wp_get_attachment_link', 'galleryWIthClass');
function galleryWithClass($src) {
$args = array(
    'post_type' => 'attachment',
    'numberposts' => null,
    'post_status' => null,
    'post_parent' => get_the_ID()
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
$alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
$html= str_replace('<img', '<img class="'. $alt.'" ', $src);
return $html;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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