• Hello, I’ve been searching unsuccessfully for a function to automatically link all the_content images to their Media File URL so this doesn’t have to be done manually in the interface for hundreds of existing images. Since these are images displayed via the_content I don’t have access to the markup to do so in my theme like I would with post thumbnails. Once the images are linked to their full size media file I can make them open in a lightbox.

    The closest I’ve come is wrapping images in a span.

    function filter_images($content){
      return preg_replace('/<img (.*) \/>\s*/iU', '<span class="className"><img \1 /></span>', $content);
    }
    add_filter('the_content', 'filter_images');
    

    Would this be the way to also link to the media file URL? I can see how I’d wrap the image in a link but not sure how I’d get the actual URL to use as the src. The image may not be an attachment to this exact post so we can’t lean on that.

    Any info is appreciated!

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    For the original Lightbox by L. Dahkar, thumbnail img tags are wrapped with an anchor tag which contains the attribute “data-lightbox”. The anchor tag’s href attribute links to the larger sized image file. You should be able to construct the full sized image filename by stripping out the size elements which WP adds to down sized images. If the thumb’s filename is foobar-150×150.jpg, we can use regexp to capture only the “foobar” and “.jpg” portions, ignoring the “-150×150” part, and construct the full size filename foobar.jpg.

    It’s not ideal, there are potential filenames that the regexp may not handle correctly. There should normally be an img tag class attribute like wp-image-1234 where 1234 is the image’s attachment ID. With the ID extracted via regexp, you can use wp_get_attachment_image_src() to reliably determine an attachment’s URL for its full (or any desired) size.

    The drawback is a query needs to be made for every image, slowing down page requests. The less reliable regexp only approach ought to be faster. Ideally, this should all be done when the image is inserted into the editor, instead of doing so after the fact through “the_content” filter. For the older “classic” editor, there is a filter we can use to alter the HTML of media insertions. For the newer block editor, I don’t know what might accomplish a similar mechanism. It might require a custom “Lightbox” block to use in place of the usual image block when one wants lightbox functionality.

Viewing 1 replies (of 1 total)
  • The topic ‘Automatically Link all Images to Full Size for Lightbox’ is closed to new replies.