AndreyGrin
11/23/2015 - 10:27 AM

Adding some extra class for Wordpress linked images in content

Adding some extra class for Wordpress linked images in content

<?php
function give_linked_images_class($content) {
        // Separate classes with spaces, e.g. 'img image-link'
        $classes = 'wplightbox';

        // check if there are already classes assigned to the anchor

        // 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;
    }

    add_filter('the_content', 'give_linked_images_class', 10, 8);
?>