I want to add a class to the anchor tag of the HTML5 gallery, so I can use a lightbox plugin, but I do not know how to do that, i've tried with the code below, but without success.

add_filter('wp_get_attachment_link', 'html5', array( 'gallery', 'caption' ));

$link = "<a class='gallery-link'></a>";

1 Answer 1


f you mean to add a class on the anchor image wrapper that you have added using wp-editor then you could add folllowing code : this will filter the content and add class to your image

function add_class_to_gallery($content) {

      $classes = 'gallery-link';         
      // check if there are already a class property assigned to the anchor
      if ( preg_match('/<a.*? class=".*?"><img/', $content) ) {
        // If there is, simply add the class
        $content = preg_replace('/(<a.*? class=".*?)(".*?><img)/', '$1 ' . $classes . '$2', $content);
      } else {
        // If there is not an existing class, create a class property
        $content = preg_replace('/(<a.*?)><img/', '$1 class="' . $classes . '" ><img', $content);
      return $content;

And if you were trying to add a class to the feature image then you could use:

<?php if (has_post_thumbnail()) : ?>    
    <a href="<?php the_permalink(); ?>" class="gallery-link" title="<?php the_title_attribute(); ?>" target="_blank"><img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_title_attribute(); ?>"/></a>
<?php endif;?>  
  • Did not work. I want to change the gallery output located in wp-includes/media.php. Just adding a class to the anchor tag. May 3, 2017 at 15:59

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.