WordPress, Lightbox and InstantClick

1 minute read

In an earlier post I explained how to speed up WordPress using InstantClick. InstantClick is a great JS library, but it may break some things. This is usually easy to fix, but in WordPress’ code mess it may take some time to figure out which files you should edit to fix something.

This fix is targeted for WordPress 3.9.1 + Responsive Lightbox + InstantClick 3.0.1.

The problem

InstantClick preloads all links by default, with some exceptions:

Some links are already blacklisted internally, and can’t be whitelisted:

  • Links with a target or download attribute.
  • Links with a different domain or protocol.
  • Links pointing to an #anchor on the same page.

All Lightbox does is hook up to the image link. When you click on an image in your post, Lightbox will prevent the default action from happening (opening the file directly) and show it in a Lightbox instead.

There are 2 problems caused by InstantClick:

  • InstantClick will preload the image and override Lightbox, so the image will open directly.
    • Can be fixed by adding a data-no-instant attribute to all image links.
  • InstantClick will only change the <body> section of the page, causing Lightbox not to hook up after changing pages. This is because Lightbox makes use of jQuery’s on document ready event, which isn’t triggered after changing pages because the page didn’t really get loaded (it was changed by InstantClick).
    • Can be fixed by loading jQuery inside the <body> section so that it gets loaded again when changing pages.

Fixing lightbox

This fix requires a minor edit in your WordPress core files. Please make a backup before editing!

I’m sure there is a better way to do this, but this is the best I came up with so far. If I find a better method I’ll update this post or create a new one. If you know a better method: feel free to contact me.

  • Edit wp-includes/post-template.php
  • On line 1439, edit the following:
    return apply_filters( 'wp_get_attachment_link', "<a href='$url'>$link_text</a>", $id, $size, $permalink, $icon, $text );
    

    to

    return apply_filters( 'wp_get_attachment_link', "<a href='$url' data-no-instant>$link_text</a>", $id, $size, $permalink, $icon, $text );
    
  • Save the file
  • Edit wp-content/<your theme>/header.php
  • Place the following line right under the <body> tag:
    <script type='text/javascript' src='http://example.com/wp-includes/js/jquery/jquery.js?ver=1.11.0'></script>
    

    Replace http://example.com/ by the URL of your WordPress installation

  • Save the file

That’s it. Lightbox should work now.

Updated:

Leave a comment