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);

Hi Jonathan

I have tried the code but I am not getting it to work. Clicking the image just opens it the regular WordPress way. Hopefully there is an easy fix for it.

Thanks!


Hey Paal. Give this a try

add_filter( 'image_send_to_editor', 'add_lightbox_to_image_in_editor', 10, 8 );
function add_lightbox_to_image_in_editor( $html, $id, $caption, $title, $align, $url, $size, $alt ) {

    $img_size = wp_get_attachment_image_src( $id, 'full' );

    if ( $url === $img_size[0] ) {

        $html = str_replace( '<a href', '<a data-uk-lightbox href', $html );

    }

    return $html;
}

Thank you Trevor! Not working yet, but I am hopefully soon there..:)

This is what I did.

I enqueued:

add_action( 'beans_uikit_enqueue_scripts', 'lightbox_example' );
function lightbox_example() {
         beans_uikit_enqueue_components( array( 'lightbox' ), 'add-ons' ); 
}

Then added:

add_filter( 'image_send_to_editor', 'add_lightbox_to_image_in_editor', 10, 8 );
function add_lightbox_to_image_in_editor( $html, $id, $caption, $title, $align, $url, $size, $alt ) {
    $img_size = wp_get_attachment_image_src( $id, 'full' );
    if ( $url === $img_size[0] ) {
        $html = str_replace( '<a href', '<a data-uk-lightbox href', $html );
    }
    return $html;
}

It did not work using WordPress 5.0. I feel like I am missing just a little thing which I have not been able to locate yet.

Write a reply

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