WordPress: Aggiungere una Classe CSS automaticamente alle immagini

WordPress: Aggiungere una Classe CSS automaticamente alle immagini

Adding class to WordPress linked images

An enduring issue with linked images, 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 (), 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;