uiKit lightbox for post content images.


It took me quite an embarassing amount of time to figure out how to properly add a lightbox to page and post content images so I thought I should share it for others. The question did come up in the beans community a couple of times without a real answer so here is mine.

The hard part for me was to get it to add the lightbox image link if, and only if, you choose Link To Media File, and also to get it to insert the image at the correct size. Here you go:


// add uikit lightbox
add_action( 'beans_uikit_enqueue_scripts', 'enqueue_uikit_lightbox_asset' );
function enqueue_uikit_lightbox_asset() {
        beans_uikit_enqueue_components( 'lightbox', 'add-ons' );
}

// add the lightbox to content images
function filter_image_send_to_editor($html, $id, $caption, $title, $align, $url, $size, $alt) {

    // get the proper width, height, and attributes for the image
    $img = get_image_tag($id, $alt, $title, $align, $size);

    // only apply uiKit lightbox if image is set to link to media file
    $image_href = wp_get_attachment_url($id);
    if ($image_href == $url ) {
        $html = '<a href="'.$url.'" data-uk-lightbox="" data-lightbox-type="image">'.$img.'</a>';
  };

  return $html;
}

add_filter('image_send_to_editor', 'filter_image_send_to_editor', 10, 8);

Write a reply

Login or register to write a reply, it's free!