Try Tuts+ Premium, Get Cash Back!
How to Integrate prettyPhoto with Post Images in your Themes

How to Integrate prettyPhoto with Post Images in your Themes

Tutorial Details
  • Program: WordPress
  • Version (if applicable): 3.3+
  • Difficulty: Easy
  • Estimated Completion Time:20 minutes

prettyPhoto is a lightbox plugin made by Stéphane Caron. Today we’re going to learn how to ship the plugin with your WordPress themes.


Introduction

Giving a built-in lightbox option instead of making users download a plugin has many benefits for theme authors. For me it’s being able to theme the lightbox to suit my WordPress themes. It’s also a nice feature to have available to your theme’s users, of course you should also give them an option to disable the functionality. With that said let’s get to it.


Step 1 Download prettyPhoto and set up directory structure

Head over to margins for-errors.com and download the plugin. Once you’ve got it we’re going to create a new directory structure for the plugin to make things easier for ourselves.

First let’s delete a few things we don’t need. In the images folder delete everything apart from the prettyPhoto folder and it’s contents. In the root folder, delete the file xhr_response.html and index.html. Now move jquery.prettyPhoto.js from the js folder to the root plugin folder and delete the js folder.

Finally, rename the folder to prettyPhoto and upload the folder to your theme’s directory, you probably already have a js or scripts directory so upload to that, for this tutorial let’s presume it’s in your-theme/js


Step 2 Add the scripts to your theme (Updated: See comments below)

Before we load up the plugin files in our theme we need to load jQuery. We’re going use the Google hosted version of jQuery using the method shared on Digging into WordPress, so let’s add the snippet to our functions.php.

if (!is_admin()) {
	add_action("wp_enqueue_scripts", "register_scripts", 11);
}
function register_scripts() {
	wp_deregister_script('jquery');
	wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
	wp_enqueue_script('jquery');
	
	wp_register_script('prettyPhoto_script', (get_bloginfo('stylesheet_directory')."/js/prettyPhoto/jquery.prettyPhoto.js"));
	wp_enqueue_script('prettyPhoto_script');
	wp_register_script('customprettyPhoto_script', (get_bloginfo('stylesheet_directory')."/js/prettyPhoto/customprettyPhoto.js"));
	wp_enqueue_script('customprettyPhoto_script');
}

You might want to consider the advantages and disadvantages of using a CDN to serve jQuery. WordPress does ship with a copy of jQuery but using Google’s hosted version may benefit your site’s performance. If you’re a theme author I would stick with using the shipped version. Check out the discussion on another tutorial to help you make up your own mind.

You’ll notice we’ve added another file called customprettyPhoto.js. This is where we’ll be making the plugin play nice with our post images and initialising it. So let’s create that file and put it in your prettyPhoto directory. OK, let’s initialise prettyPhoto.

<script>
  $(document).ready(function(){
    $("a[class^='prettyPhoto']").prettyPhoto();
  });
</script>

We need to add a line of jQuery to add the required prettyPhoto class prettyPhoto to the anchor tags that surround our post images. Since we’re talking jQuery let’s use it to accomplish this. Add the following right after $(document).ready(function(){ where we make sure the page is loaded.

$('.entry-content a').has('img').addClass('prettyPhoto');

Replace .entry-content with whatever class name or ID you’ve wrapped your post content with and you should have successfully added the class to all links that wrap your post images. If you had a look at the documentation for prettyPhoto you will see it says to use a rel attribute but instead we’ve used a class. Doing so prevents validation errors in our HTML because rel attributes can only have certain allowed values according to the HTML5 spec.

Next we want to enable prettyPhoto’s description option. We have to overcome one small hurdle which is that prettyPhoto wants us to add title attributes to our anchor tags that will be used for the descriptions but WordPress adds titles to image tags. To solve this we’ll write a couple lines of jQuery that will take the image title tag and set the same title on the anchor tag that wraps the image.

$('.entry-content a img').click(function () {
	var desc = $(this).attr('title');
	$('.entry-content a').has('img').attr('title', desc);
});

Here we fire a function when the user clicks on a post image. We grab the image’s title tag and attach it to the anchor. This step makes it a lot easier for your theme’s users to add descriptions. If you want to disable the functionality altogether just make sure to set each anchors title to be empty, if it’s totally missing, as in there isn’t even an empty title, prettyPhoto will just display “undefined” instead.


Step 3 Add the prettyPhoto CSS to your theme

We need to add the CSS for prettyPhoto to the theme. Back to your functions.php file and add the following line to the top:

wp_enqueue_style('prettyPhoto', get_bloginfo('stylesheet_directory').'/js/prettyPhoto/css/prettyPhoto.css');

Since we kept the images and CSS in their original folders and relative to each other as they were originally we don’t need to worry about broken images.


Step 4 Captions and Titles

Let’s look at how to add captions and titles that our prettyPhoto will use. Looking at the image above we can see the relationship between the post image alt tag and link title tag we can set when adding an image to a post or page.


Finishing Up

And that’s it, we’ve successfully added prettyPhoto to our theme. Make sure to read the plugin documentation for more uses and options. PrettyPhoto can handle more than just images, it works with videos, ajax and more. It also ships with a handful of themes that may suit your theme out of the box or at least give you a good starting point.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.guillaumevoisin.fr Guillaume

    Why don’t you use wp_enqueue_style and wp_enqueue_script instead of printing directly the script in your theme file. @import is also not recommended (http://www.stevesouders.com/blog/2009/04/09/dont-use-import/).

    PrettyPhoto is a nice jquery gallery though.

    • http://barrywalsh-portfolio.com Barry

      Hi Guillaume, I didn’t use wp_enqueue_script in the head to show how to load from jQuery from google’s CDN instead of using the copy that comes with WordPress. And I wasn’t aware of performance issues with using @import, cheers for the link, interested read! I’ll have a proper read and write a small update on the post.

    • http://www.damiencarbery.com Damien

      On a similar note, why wp_deregister_script jquery – is it for parallel loading? jQuery 1.7.1 is in WordPress 3.3.1.

      • http://barrywalsh-portfolio.com Barry

        It just make sure you’re loading from the CDN and not the shipped version of jQuery with WordPress. By all means there’s many ways of adding jQuery this is just one technique for loading it from google’s CDN. From the codex it..”De-registers the WordPress stock jquery script, so you can register your own copy or from the Google CDN”.

  • http://www.mojowill.com theMojoWill

    Nice idea but really badly written, PrettyPhoto is nice but PLEASE PLEASE PLEASE follow WordPress coding standards, as a large site you really have a responsibility to publish the right information.

    Enqueue your scripts, don’t tell people to use remote jQuery without providing the pros and cons, don’t @import in your css ENQUEUE it.

    PrettyPhoto = Great
    This article = Fail

    • http://barrywalsh-portfolio.com Barry Walsh

      Cheers for the comment although explaining what you’re saying would also help.

      The script is still being enqueued, can you explain what you mean there? If you want to talk about pros and cons of using a CDN then list them in your comment to open discussion. As for @import, I’ll be updating tutorial.

      As for WordPress standards, the CDN snippet is mentioned in the codex twice. http://codex.wordpress.org/Function_Reference/wp_enqueue_script and http://codex.wordpress.org/Function_Reference/wp_deregister_script

      • http://www.mojowill.com theMojoWill

        I see that your tutorial has been updated to include pros and cons of using a CDN, all I wanted. Likewise I see you have moved your custom js to a separate file and enqueued it. That and properly adding the css now looks like a proper tutorial!

        • http://barrywalsh-portfolio.com Barry

          Cheers for keeping me on my toes and for improving the quality of the tutorial.

  • http://muaradesign.com kipas

    hi, thanks for tutorial,

    can you help me to insert the comment form on the image which viewed in prettyPhoto mode? in your tutorial we can see the “Title” and “Alternate Text” image in prettyPhoto mode and we can see the facebook and twitter button too…

    I think this is the same as facebook images view…

    i think we can do like insert the “attachment page” (with modify, view only the image and comment form) in prettyPhoto view, in edit on Gallery Settings, Link thumbnails to: Attachment Page ([gallery id="" ]), not [gallery id="" link="file"]

    can you help me….

    thanks…

  • Pingback: How to Integrate prettyPhoto with Post Images in your Themes | Shadowtek | Hosting and Design Solutions

  • Japh Thomson
    Staff

    Thanks everyone for your comments so far! We’ll be adjusting the article to address things mentioned so far, such as the use of @import, and the enqueuing of “jquery.prettyPhoto.js”

    Regarding the reasons for loading jQuery from Google’s CDN instead of using the packaged version, see this great discussion on Stack Overflow: http://stackoverflow.com/questions/2180391/why-should-i-use-googles-cdn-for-jquery

  • Norm

    It didnt work completely for me. I may have messed somethings up along the way. Would be helpful if you had a section that shows ALL the code to add to functions.php, all together, instead of piece meal. At one point you even say add this, then you say add this also but before the other code, which may have led to some confusion. I click on the image and it darkens the screen and something starts to pop up but its small and says, “NULL, Undefined” in the area where the photo should be. So something is off somewhere. And would be easier for me to know if I did it right if all the code was in one place.

    thanks though, Ill spend more time troubleshooting later.

  • http://www.wpexplorer.com/ AJ Clarke

    Adding the prettyPhoto class to all links with an img is not such a good idea as what if someone wanted to link their image to an external site? It will open this in lightbox…no bueno.

    • http://barrywalsh-portfolio.com Barry

      Good point although this tutorial is about applying it to post images not site wide images.

  • Aleksandar

    Ok i finally made it work. Although this tutorial was very helpful but not exactly working for me. For example step 2 is not working. implementation of prettyphoto in functions.php file won’t work for me, i don’t know why i used same method to implement superfish menu with deregister script and register latest jquery and registering superfish script and that worked, registering prettyphoto script not working. I had to manually add prettyphoto files in theme header. Also customprettyPhoto.js is not working. When i add script in header it works, when i add link to customprettyPhoto.js in header it doesn’t work. and code in customprettyPhoto.js is little bit confusing for those who don’t know much of coding. In tutorial you have explanation to add 2 functions and although you didn’t mention that you need to close one function than add other, from the look people will assume that you need to create customprettyPhoto.js like this

    $(document).ready(function(){
    $(‘.video-wrapper-in a’).has(‘img’).addClass(‘prettyPhoto’);
    $(“a[class^='prettyPhoto']“).prettyPhoto();
    });
    $(‘.video-wrapper-in a img’).click(function () {
    var desc = $(this).attr(‘title’);
    $(‘.video-wrapper-in a’).has(‘img’).attr(‘title’, desc);
    });

    but instead its function inside function, and code should look like this (or at least it worked for me like this)

    $(document).ready(function(){
    $(‘.video-wrapper-in a’).has(‘img’).addClass(‘prettyPhoto’);
    $(“a[class^='prettyPhoto']“).prettyPhoto();
    $(‘.video-wrapper-in a img’).click(function () {
    var desc = $(this).attr(‘title’);
    $(‘.video-wrapper-in a’).has(‘img’).attr(‘title’, desc);
    });
    });

    Yea and also code is working only in last class before images.
    If you have class=”post-page” than class=”post-inside” you have to add “post-inside” to customprettyPhoto,js file otherwise it won’t work like if you style “post-page a” it’s style also applied to “post-inside a” links. With customprettyPhoto,js is not same case.

    Im not making critics here because this is only 1 tutorial i found helpful on how to implement prettyPhoto in wordpress to be automatic. These are only problems i run into when i tried to implement it as beginner wordpress developer.

  • http://bowesales.com Jesse

    Thanks for the help with this tutorial.

    I’m customizing a theme and currently came across a problem that I can’t solve. Any idea how to initialize a gallery with prettyPhoto in WordPress?? I have a group of images and inserted a gallery through the media panel in the dashboard but prettyPhoto won’t give me the controls to scroll through images. I know I need to have a rel [gallery] attribute to the anchor and wondering if this can be done through the cusstom js file but not sure what to add or how.

    Also found that downloading the prettyphoto.js files from their github page here https://github.com/scaron/prettyphoto/blob/master/js/jquery.prettyPhoto.js fixed the ‘Undefined’ title issues.

    Thanks again for this tutorial and if you can help I will be greatly appreciative.

    Jesse.

    • http://bowesales.com Jesse

      Well, Hello again!

      I figured out what I was trying to achieve. If anyone had trouble initializing the rel=”prettyPhoto[gallery] part of the plugin, heres how I did it.

      In the customprettyPhoto.js file

      $(document).ready(function(){

      // add class to anchor eg. .post a
      $(‘.full-width-post-content a’).has(‘img’).addClass(‘prettyPhoto’);
      $(“a[class^='prettyPhoto']“).prettyPhoto();
      $(‘.full-width-post-content a’).has(‘img’).attr(‘rel’, ‘[gallery]‘);

      • http://bowesales.com Jesse

        ^ Sorry!

    • http://bowesales.com Jesse

      Well, Hello again!

      I figured out what I was trying to achieve. If anyone had trouble initializing the rel=”prettyPhoto[gallery] part of the plugin to be able to click through the images on a page, here’s how I did it.

      Following the tutorial and setting everything up as explained I sorted my customprettyPhoto.js file as follows:

      $(document).ready(function(){

      $(‘.entry-content a’).has(‘img’).addClass(‘prettyPhoto’);
      $(“a[class^='prettyPhoto']“).prettyPhoto();
      $(‘.entry-content a’).has(‘img’).attr(‘rel’, ‘[gallery]‘);

      $(‘.entry-content a’).click(function () {
      var desc = $(this).attr(‘title’);
      $(‘.entry-content a’).has(‘img’).attr(‘title’, desc, ‘rel’, [gallery] );

      });
      });
      });

      Now I have a working gallery when more than one image is added to a single post or page.

  • http://google-plus-info.blogspot.com/ G+ Info

    wow, it’s very awesome! Nice effects! I’ll try to my wordpress blog. thanks!

  • Melanie

    Wow, I was looking for some info on prettyPhoto and thought I’d read this tut. Just to find out that it is so poorly written. Do you realize right after

    You’ll notice we’ve added another file called customprettyPhoto.js. This is where we’ll be making the plugin play nice with our post images and initialising it. So let’s create that file and put it in your prettyPhoto directory. OK, let’s initialise prettyPhoto.

    You lose maybe most users? You don’t even state where the snippets go exactly. Does everything go in the function file? Does this go in the header, does this one go in the footer?

    That’s pretty bad.

    • Barry Walsh

      The script is registered and enqueued in your functions.php, unless I’ve picked you up wrong on the problem you’re pointing out? customprettyPhoto.js is registered and enqueued in the code block above the paragraph you quoted.

    • http://n/a Nana

      Melanie, totally get what you are saying because I was thinking the same about this paragraph. I must have read it 10 times and still don’t get the meaning. It is very confusing, however it seems perfectly fine to the author and others who know what he is talking about, but only Aleksanders comment helped me understand that part :)

      I think this tutorial could benefit from some serious re-write to make things A LOT clearer than it is, ie what Norm said, explain it block by block.

      I have still not managed to get pretty photo to work, and I don’t know what the cause is. I can see that it is calling the jquery (both files) just fine, but it fails to add the prettyPhoto class to the image/link. I have also tried the other version, installing the files in header and before the end but that also doesn’t do the trick. Maybe it’s a conflict, or a tiny thing I am missing, but my knowledge doesn’t get me further than this.

  • Jeff

    Wow this is poorly written. I expect better from this website.

  • Pingback: How to Integrate prettyPhoto with your WordPress Theme | Bowe

  • http://applesiam.com Ali

    I don’t know why people do complain a lots?

    If you feel this is poor written or not really get what you want then just leave.

    I think we should instead say thank you to the author who working hard to get some good information even thought it might not suit what you want, but it does for many people.

    These people need to get some life seriously.

  • http://www.webmasteradvance.com tantan

    This code is working, but I don’t create a file called customprettyPhoto.js.
    I just add this code at the end before closing of body tag ()

    $(document).ready(function(){

    $(‘.entry a’).has(‘img’).addClass(‘prettyPhoto’);

    $(“a[class^='prettyPhoto']“).prettyPhoto({
    theme: ‘pp_default’, /* light_rounded / dark_rounded / light_square / dark_square / facebook / pp_default */
    social_tools: ” /* html or false to disable */
    });

    $(‘.entry a’).has(‘img’).attr(‘rel’, ‘prettyPhoto[gallery]‘);

    $(‘.entry a’).click(function () {
    var desc = $(this).attr(‘title’);
    $(‘.entry- a’).has(‘img’).attr(‘title’, desc, ‘rel’, [gallery] );
    });

    });

  • http://webagate.com/demp/stratum shahid

    thanks this is nice hint…

    • Ant

      Hi,

      Interesting post but as a tutorial not the best laid out, considering it is marked as easy! You don’t appear to state where the prettyPhoto initialisation code goes, it would also be good to see what the final customprettyPhoto.js file looks like, as there is some confusion as to what this contains and judging by the comments a lot of people have had an issue with this!

  • Mary

    Hey,

    nice post and really the only one available for PrettyPhoto that helps. I’m using wp theme that already have PrettyPhoto implemented, but as hard I’m trying I cannot make the caption appears.
    Should I put this code into the custom js of Prettyphoto and do I have to change something already existing there.
    $(‘.entry-content a img’).click(function () {
    var desc = $(this).attr(‘title’);
    $(‘.entry-content a’).has(‘img’).attr(‘title’, desc);
    });

    or Do I have to set it all from the beginning in order to receive it correctly?

    Thank you!

  • http://www.KelvinAlf.com Kelvin

    In case anyone is looking for how to make the wordpress gallery default to linking to the image file:

    function galleryLink() {
    return do_shortcode(‘[gallery link="file"]‘);
    }

  • zivjc

    Awesome post once again! I am making a plugin that uses prettyphoto and this is just what I was looking for.

  • http://www.newsworldinside.com/ News World Inside

    it doesn’t work on my blog :(

  • Pingback: How to develop a Wordpress Theme - WordPress Theme Development Tutorials