wordpress snippets last updated   : April 22, 2014
we now have 631 snippets

Add a custom class to wp_get_attachment_link

wordpress snippet

Adding this snippet to the functions.php of your wordpress theme will add a custom class to wp_get_attachment_link.

snippet :  PHPcopy
function add_class_attachment_link($html){
    $postid = get_the_ID();
    $html = str_replace('<a','<a class="wpsnipp"',$html);
    return $html;
}
add_filter('wp_get_attachment_link','add_class_attachment_link',10,1);
source →
  • John B

    awesome you made my day, really

    • http://wpsnipp.com Kevin Chard

      Cool glad to hear it John, I post snippets everyday so lets hope I can make your day again. :) enjoy the snippets.

  • Muditha

    Fantastic! Just what I was looking for.

    • http://wpsnipp.com Kevin Chard

      I figured you needed this Muditha, ;) enjoy the snippet glad to hear you like it.

  • Gerald Nathaniel

    Hi Kevin, Mind telling me how did you think of this snippet ? I want to learn more about how you came up with this. 

  • Matt Guy

    Thanks for the snippet. I looked for it because I would like to add a custom class to links produced by wp_get_attachment_link working in /wp-includes/media.php (I want to add a specific class name to images made by the default wp gallery for lightbox). Where should I put a link like this?

    Also, how can I make sure the class doesn’t appear in every instance of wp_get_attachment_link? Can I make it conditional?

    Thanks again!

    • http://wpsnipp.com Kevin Chard

      Hi Matt, If you are going to want to make things conditional you will be best to make your own shortcode to display images. This snippet just finds each link and adds a class,

      • Matt Guy

        Sorry, I meant to add class to the link itself, as required by a lightbox plugin i’m working on. /wp-includes/media.php uses wp_get_attachment_link to create its links, so this would be good. It wouldn’t actually need to be conditional either. Just make the gallery links have a class of thumb. Only it doesn’t seem to work when placed in the theme functions file, possibly because media.php which created the gallery links is in /wp-includes. I tried sticking your snippet in /wp-includes/functions.php and inside of media.php, which didn’t seem to work, maybe I did it wrong. What do you think? Your snippet is probably perfect, I just need to find the right slot!

  • Julian K

    life saver :P

  • http://www.facebook.com/lukas.riepler Lukas Riepler

    Thank you for that snippet! I am looking for a way to change the class of the function “wp_get_attachment_image” in the functions.php. Do you know how to do that?

  • Daniel

    Thank you for this snippet!

  • Calvin Williams

    Cheers to you for this snippet, it helped me solve a really annoying issue!

  • Matthew89

    Thanks a lot! :)

jqsnipp.com | we just launched jquery snippets website