Insight & Insanity

web development with a dash of life

Use Magnific Popup with WordPress Now

Although you can still follow this method, there is now an unofficial plugin available found here: http://ajtroxell.com/magnific-popup-wordpress-plugin. Please install this to get the below functionality without all the hassle.

Magnific Popup in WordPress
Magnific Popup, advertised as “Magnific Popup, A Truly Responsive Lightbox (For jQuery And Zepto.js)”, is a open-source lightweight lightbox plugin that boasts progressive image loading, CSS based resizing, preloading of adjacent images in galleries, high-dpi support, and a slew of other features.

Released only a short while ago, but already receiving praise on sites such as Smashing Magazine, Magnific Popup really is all it is cracked up to be.

One downside, at least for the time being, is that the only option for WordPress users is to install it yourself rather than using a plugin, with the latter being the easiest method. The way in which Magnific Popup loads images makes WordPress implementation more difficult than adding a couple of scripts to your site.

Being impatient and wanting absolute control of what is added to my sites header/footer, I decided to go ahead and implement Magnific Popup myself. It is rather simple and here is how it is done.

Basic Install

A simple install to get things working in a flash.

Download & Install Magnific Popup

Head on over to the GitHub page and download magnific-popup.css, as well as either jquery.magnific-popup.js or jquery.magnific-popup.min.js and upload them to your current theme folder.

This may vary depending on your theme configuration, but you should use something like this to insert the CSS file into your header:

And this to insert the JS into your footer:

Get it Initialized

Initializing Magnific Popup is really simple, but for WordPress you will need to initialize it for inline images as well as galleries.

You can place this in a file and call it below the jquery.magnific-popup.js using<script type="text/javascript" src="<?php echo get_stylesheet_directory_uri(); ?>/jquery.initialize.js"></script>, or simply place it inline.

Editing Your Functions

Now you have working galleries, but your single images still won’t open right? This is due to wordpress not inserting any class to a tags (containing images) by default. Magnific Popup needs a class in order to initialize these elements, so you must add one by editing the functions.php file.

This simple snippet, when added to your functions.php file will add class of “pop” to all images that are linked to a larger version.

If you have any other lightbox plugins installed it would be a good idea to disable them as they are no longer needed.

Enqueue Scripts

Instead of calling the scripts directly like I have done in the example, you can enqueue them in your functions as suggested byJohn in the comments.

Method #2 via Heracles Papatheodorou

If you choose this method you can enqueue this script instead of what is posted above. You can also ignore editing your functions to add a class to single images.

Implementing Image Title and Descriptions (galleries)

Mike Ill Kilmer asked if it was possible to add image titles and descriptions, and the answer is yes, but it is not as easy as i’d like it to be.

Title Tags

Wordpress, starting at version 3.7 (as far as I know), removed image titles from galleries. So we have no attribute to reference, even if we wanted to. Luckily there is a way to bring the title tag back for us, just place this in your functions.php file.

Now we have titles showing in our a tags, so what do we do with it now?

Well, with the help of the Magnific Popup documentation we can utilize the callback functionality and add some custom markup. In place of the jquery.initialize.js from above, use the following code, which I will explain.

Callbacks

In the callbacks section we instruct MFP (magnific popup) to populate the .mfp-description div with the title attribute from this.currItem.el (current active item link) on open, and then clear and repopulate it for each change of our active image. Our title is set withintitleSrc: as it was before, but we will be making some changes to that as well.

Markup

Markup allows you to do exactly that, specify your own markup. From what I understand, you can’t just interject markup, you have to specify the exact markup for the entire MFP display. The only difference here from what MFP renders by default is the addition of the mfp-description element. This is where we place our “caption” for the active image. I have used inline styling to match the default MFP styling, but you can place it in a stylesheet if you prefer.

titleSrc

We now need to change our titleSrc element from the previous “alt” value to something a little more complex.



404 Not Found

Error: Not Found

The requested URL / was not found on this server.

What we’ve done here is populated our titleSrc with the alt attribute of each image in our gallery, and surrounded it with strong tags so it stands apart from our descriptions a bit more.

So what have we accomplished?

  • Added title tags back to WordPress images.
  • Told MFP to populate a .mfp-description element with our current image links title attribute value.
  • Set our image title to the alt attribute value of the current image.
  • You can see it in action on this page (http://ajtroxell.com/squar3d-v2/). Keep in mind I didn’t go back and make sure my title/captions were formatted properly.

Now for each image in your gallery you will need to give it a title and caption within WordPress, and you are ready to go.

There You Have It

Magnific popup now works in WordPress (now with titles and descriptions), and you don’t even have to wait for an official plugin. You can see both inline images and galleries working on this page.

Discussion

  • icoup

    I’ve followed your steps to add Magnific to my site, but inline images and galleries still don’t work. Is there some modifications that need to be made to the scripts to work in WordPress? I ask because I know WP runs jQuery in noConflict mode.

    • http://ajtroxell.com/ AJ Troxell

      I would be more than willing to help you out. Email me aj@ajtroxell.com and we can correspond that way.

  • Matthew Kilander

    How would you get the videos to work like Youtube for example?

    • http://ajtroxell.com/ AJ Troxell

      Are you inserting YouTube files automatically? Or just manually inserting video links in posts/pages?

      • Matthew Kilander

        Automatically, just like how you did it for the images. I can’t figure out the code to do it, so maybe you knew how.

        • thamamur

          I’d like to know how to use “Popup with video or map” in WordPress too!

          • http://ajtroxell.com AJ

            You can use the documentation to do this. Are you looking to open all videos or specific links like this? I’d love to throw something together but I’d need more details.

  • http://ajtroxell.com/ AJ Troxell

    Awesome man. I should have put that down in my tutorial. I precompile all of my files into master.css and master,js files before being sent to the server, so I guess I was only thinking of myself. Mind if I embed your gist?

    • John

      Go for it! Glad to contribute! :)

  • http://archi.tect.gr/ Heracles Papatheodorou

    After a couple of hours struggling with regex and PHP’s DOMDocument to make “addlightboxrel_replace()” work with links that already have a class attribute, I came up with —what should be the obvious— a simple jQuery selector: http://pastebin.com/bhf0uzN5

    Put straight into your initialization script (with an extra twist to avoid noConflict errors) I believe it makes for a much more elegant than running the whole post through regex :)

    Well done for your post however, it’s a great workaround till the official plugin comes!
    Kudos to John as well, for the enqueue tip.

    • http://ajtroxell.com/ AJ Troxell

      Unfortunately I could not get your script to work. It seems as though initializing the images before the galleries causes magnific to assume that all images are single images, thusly ignoring the galleries. I came up with this, which seems to accomplish the task: http://pastebin.com/mBbubEX7

      • http://archi.tect.gr/ Heracles Papatheodorou

        Oh you’re right, I didn’t think of the galleries!
        Re-modified it once more to only loop through the selectors once and also create separate groups for each gallery tag: http://pastebin.com/s3rT3FBr

        • http://ajtroxell.com/ AJ Troxell

          Added this method to the tutorial. Thanks for your work!

          • http://archi.tect.gr/ Heracles Papatheodorou

            Thank you again for the original method and article, glad to contribute my 2 cents.

  • Anthony Jr.

    So glad I came across this page. Between the help of the three contributors – I fixed a ton of lightbox speed issues loading large images on my photography website. It took me some time to understand where all the code was supposed to be placed (not a real web developer, but passionately curious). Though, now that it’s all implemented… Magnific Popup is no joke. You all really made my day.

  • premiumwd

    why not put all, why just gallery?

    • http://ajtroxell.com/ AJ Troxell

      For galleries magnific requires you to specify the containing element of a gallery to ensure navigation etc…

      The other part of the JS is what tells magnific that all other image links are single images utilizing magnific.

  • Emir Ribi?

    Hey,

    Is there a way not to display a gallery on a post, but only put a link to it. When someone clicks the link, it opens the gallery in a lightbox?

    • http://ajtroxell.com/ AJ Troxell

      I will be looking into this for you soon, sorry about the wait!

  • Mirjam

    Thanks! This works fine but I would like to implement it within the Royal Slider Plugin.

    Does someone know how to use this with the Dmitry Semenov “WordPress Royal Slider” plugin?
    Magic Popup works fine in wordpress but there are no arrows next and prev in the Popup for the gallery.

    This part of code doesn’t seem to work.

    //gallery popup
    $(‘.gallery’).each(function() {
    $(this).magnificPopup({
    delegate: ‘a’,
    type: ‘image’,
    gallery: {enabled:true}
    });
    });

  • Mike Ill Kilmer

    This is a really helpful post, AJ. Thank you. In case anyone else has a “dim” moment – the images and/or gallery images need to link to the media file in order for this to work.

    • http://ajtroxell.com/ AJ Troxell

      Correct, thanks for pointing that out!

  • Mike Ill Kilmer

    Hey AJ – Is there simple code that would add title and description from the WP database to the popup?

    • http://ajtroxell.com/ AJ Troxell

      I have added instructions on how to go about doing this in the above post. Hope it helps!

  • Mike Ill Kilmer

    You rock, AJ. Working on title additions now. Not sure why yet, but the `mfp-bg mfp-ready` div is closing before any of the additional MFP divs; “.

    • http://ajtroxell.com/ AJ Troxell

      Can you share or email me a link to the page?

      • Mike Ill Kilmer

        Hey man. it’s here: http://www.storybooksound.com/dev/album-art-test/. Using and really loving the customizr theme. Added a filter to override some of the native gallery styling.

        [code]function enqueue_gallery_style() {
        wp_enqueue_style($handle = 'storybook-gallery-styling', $src = get_stylesheet_directory_uri() . '/album-gallery.css', $deps = array(), $ver = null, $media = null );
        }
        add_filter( 'post_gallery', 'enqueue_gallery_style', 1001, 2 );[/code]
        (how do i paste code here?)

        • http://ajtroxell.com/ AJ Troxell

          Looks awesome, great work! For code in Disqus use content without the apostrophes. That should work.

          • Mike Ill Kilmer

            The enqueue_scripts code can be altered thusly to insure script loads below the footer (as long as wp_footer()) exists in the right place in the wp theme:

            add_action('wp_enqueue_scripts', 'enqueue_magnific_popup_scripts');
            function enqueue_magnific_popup_scripts() {
            wp_register_script( 'magnific_popup_script', get_stylesheet_directory_uri() . '/magnific-popup/jquery.magnific-popup.min.js', array( 'jquery' ),'1.0.0', true );
            wp_enqueue_script( 'magnific_popup_script' );
            wp_register_script( 'magnific_init_script', get_stylesheet_directory_uri() . '/magnific-popup/jquery.magnific-init.js', array( 'jquery' ),'1.0.0', true );
            wp_enqueue_script( 'magnific_init_script' );
            }

            see: http://codex.wordpress.org/Function_Reference/wp_enqueue_script

            • http://ajtroxell.com/ AJ Troxell

              Awesome work Mike, ill be adding that to the tutorial soon!

    • Mike Ill Kilmer

      didn’t determine cause of the problem, but went back to simplest install and developed 1 step at a time. working wonderfully now!

  • Pingback: tutorial on using the awesome Magnific Pop-up within wordpress | Media Zoo()

  • Pingback: Jetpack Carousel Responsive Incompatible with WP 3.7, 3.8, 3.9 | Media Zoo()

  • Pingback: Bookmarks for October 3rd | Chris's Digital Detritus()

  • http://www.benworkandplay.com/ Ben Anggoro

    Hi AJ,
    Thanks for this. I got a question. Will it be possible to leave out thumbnail images that are linked to its attachment page ‘un-lightboxed’? How do I tell the JS to do that? Thanks

  • AirBetty

    OK you had me at download and upload and dot the i, but here’s where I’m lost.

    You say under Get it Initialized, “You can place this in a file and call it below the jquery.magnific-popup.js using…”

    Do I copy the code above that begins with

    $(document).ready(function() {…

    …and then place all that coding in my functions.php folder?
    …or put it in the jquery.magnific-popup.js folder?
    …somewhere else?

    I love how-to guides and appreciate the effort you took to write this post. I’ve read the documentation on the developer’s GitHub page but that’s all…Ukrainian on me.

    Thanks!

  • Pyramid Music

    Hi, my theme already uses Magnific Popup. I just want to be able to add “captions” for each image on the popup gallery. How could I do that?

  • Chris Walsh

    I don’t understand how you got this to work. I applied the filter for wp_get_attachment_link, and it didn’t do anything. I suppose that this is not meant for images with links inside the post/page content. Any solutions for images in the content?

  • salens

    Hi, I have problem, pls if someone could help me. Magnific popup works great,except one thing,when open some image from gallery on bottom left down bellow of image is said Title is “undefined” on every picture I open, I run gallery from admin page something like this [gallery size="large" ids="287,285,284,261"], Thx for your help!

  • joshrodgers

    Hey there, the script works great, but all of the images open as single images…any way to add next and previous links?

  • Elton

    Hello. I made all the procedures, but clicking on the image gallery only the message “The image could not be loaded.” The part of the code “Your Editing Functions” is correct? It is similar to another just below your tutorial. Thanks,

  • GabbyVille

    How about the ajax function?