In my previous post I explained why it’s better to add functionality to your blog by customizing functions rather than installing plugins.
For the sake of example, I’ll present a method to add lightbox effect (FancyBox jQuery plugin to be exact) to post images without using a WordPress plugin.

The FancyBox for WordPress plugin does a good job in integrating the FancyBox jQuery plugin into your blog.
However, I don’t like the fact that the files fancybox.css and fancybox.js are loaded for each and every page in my blog, even ones that don’t have images in them!

Instead of installing a WordPress plugin, I recommend integrating the fancybox effect only for images you choose, by adding just a few lines of code to your theme files.

Add the following code to functions.php file (if you don’t have one in your theme folder, simply create the file and make sure it is stored in your theme folder).

function loadFancyBox()
{
	if (is_single() && strpos($post->post_content,'class="fancy"') !== false)
	{
		wp_enqueue_style('fancyStyle', '/wp-content/themes/yourThemeName/fancyBox/jquery.fancybox-1.3.0.css');
		wp_enqueue_script('fancyScript', '/wp-content/themes/yourThemeName/fancyBox/jquery.fancybox-1.3.0.js', array('jquery'), '', true );
	}
}
add_action('wp_print_styles', 'loadFancyBox');

The code block above adds the ‘loadFancyBox’ function to be loaded along with the WordPress ‘wp_print_styles’ function. This code is inspired by the code in Joost de Valk’s post.

Lines 3-7 specify what shall occur if the following two conditions are met:

  • The current page is a single post.
  • The post being displayed, contains the string class=”fancy” inside its HTML.

Only if both conditions are met, the css and javascript files are loaded.
To apply the effect successfully in a post, make sure to add class=”fancy” like in the following example:

<a class="fancy" href="/wp-content/uploads/2010/03/large_image_for_fancy_effect.jpg">
    <img src="/wp-content/uploads/2010/03/thumb_image.jpg">
</a>

The last thing left to do is call the jquery function for those images.
To avoid creating a separate javascript file for this call, simply copy and paste the following lines to the end of jquery.fancybox-1.3.0.js file, just before closing })(jQuery);
So the end of the file will look like this:

$("a.fancy").fancybox({
'titleShow'     : false,
'transitionIn'    : 'elastic',
'transitionOut'    : 'elastic'
});
})(jQuery);

You can then modify the transition effect and other properties according to the instructions here.

So you can see it’s really not that big of a deal to to get along without WordPress plugins for jQuery effects, even if you’re not a coder. Keeping your blog fast and clean will make your visitors happier and is definitely worth the few extra minutes of tweaking.

Topics:   | | | |