Adding class to WordPress linked images

An enduring issue with linked images (<a href=""><img src="" /></a>), is targeting the anchor link for theming—especially for disabling borders and highlighting that look great on text links but odd for images. CSS doesn't have a parent selector ( a > img:parent), and javascript feels like overkill. The simple solution is to add a class to the parent anchor (<a href="" class="img">), but that can get repetitive, especially when WordPress is supposed to automate those sorts of things.

Adding the following code to your WordPress theme's functions.php file will automatically add a class to the anchor link when you insert linked images through WordPress's Media Library interface. It won't fix posts you've already written, but should make things better moving forward.


/**
 * Attach a class to linked images' parent anchors
 * e.g. a img => a.img img
 */
function give_linked_images_class($html, $id, $caption, $title, $align, $url, $size, $alt = '' ){
  $classes = 'img'; // separated by spaces, e.g. 'img image-link'

  // check if there are already classes assigned to the anchor
  if ( preg_match('/<a.*? class=".*?">/', $html) ) {
    $html = preg_replace('/(<a.*? class=".*?)(".*?>)/', '$1 ' . $classes . '$2', $html);
  } else {
    $html = preg_replace('/(<a.*?)>/', '$1 class="' . $classes . '" >', $html);
  }
  return $html;
}
add_filter('image_send_to_editor','give_linked_images_class',10,8);

The if/else could probably be done with a single regular expression, but I'm not that smart.

Related posts:

  1. Speedgeeking on WordPress Filters Tonight I’ll be making 10 five-minute presentations about WordPress Filters, centered on this post about adding class to WordPress linked...
  2. Community mapping class interview & outcomes   Last year I interviewed Richard (Dick) Howe, Lowell’s Registrar of Deeds about the impact of his participation in a...
  3. Ambiguous URL Photo from awesome teacher @paulramsay who used PrintAndShare.org to share his classroom’s DonorsChoose Project. As a result of building PrintAndShare.org I am hyper-sensitive...

4 comments

Ben Lind #permalink

Wow, thank you SO much for this function! I’ve been pulling out my hair for hours over this problem, and now I can fix it. Thanks so much!

Jon Heslop #permalink

Awesome!

I’ve always wanted this! A 3 minute google found this.

Thank you so much!

matt #permalink

Thanks, this was exactly what I needed to ensure that my lightbox worked properly

Adam Housman #permalink

Way to go — this is really helpful, thanks.

Leave your comment