0

I'm using this code in my WordPress theme functions.php to add a "fancybox" class to linked images. However, I do not want to add the fancybox class to images that are linked to non-image URLs.

In other words: currently the script will add the "fancybox" class to an HTML structure like this (which I do not want):

<a href="http://acme.com/a-non-image-link"> <img src="http://acme.com/image.jpg" /> </a>

Where as I only want to add the class to structures like:

<a href="http://acme.com/an-image.jpg"> <img src="http://acme.com/an-image.jpg" /> </a>

or

<a href="http://acme.com/an-image.jpg"> <img src="http://acme.com/another-image.jpg" /> </a>

How can I modify the regex expression in this code to only include anchor tags whose HREF attribute contains .jpg, .jpeg, .png, or .gif?

Thank you!

        // Add fancybox class to linked images
        function add_classes_to_linked_images($html) {
            $classes = 'fancybox fancybox-img'; // can do multiple classes, separate with space

            $patterns = array();
            $replacements = array();

            $patterns[0] = '/<a(?![^>]*class)([^>]*)>\s*<img([^>]*)>\s*<\/a>/'; // matches img tag wrapped in anchor tag where anchor tag where anchor has no existing classes
            $replacements[0] = '<a\1 class="' . $classes . '"><img\2><span class="post-content-fb-btn"></span></a>';

            $patterns[1] = '/<a([^>]*)class="([^"]*)"([^>]*)>\s*<img([^>]*)>\s*<\/a>/'; // matches img tag wrapped in anchor tag where anchor has existing classes contained in double quotes
            $replacements[1] = '<a\1class="' . $classes . ' \2"\3><img\4> <span class="post-content-fb-btn"></span></a>';

            $patterns[2] = '/<a([^>]*)class=\'([^\']*)\'([^>]*)>\s*<img([^>]*)>\s*<\/a>/'; // matches img tag wrapped in anchor tag where anchor has existing classes contained in single quotes
            $replacements[2] = '<a\1class="' . $classes . ' \2"\3><img\4> <span class="post-content-fb-btn"></span></a>';

            $html = preg_replace($patterns, $replacements, $html);

            return $html;
        }

        add_filter('the_content', 'add_classes_to_linked_images', 100, 1);
1

1 Answer 1

0

The following should work with one caveat. The link needs to be on a separate line to the image tag, or the file extension of the image will create a match.

/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i

Maybe someone can improve on it rather than posting sarcastic comments :)

1
  • This seems to break if the URL doesn't have an extension at all. Do you know how to correct for that? <a href="/work/artwork"> should NOT be a match, but still is. Apr 2, 2018 at 23:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.