Personal and Professional Blog of Rich Hauck

Adding fancyBox to WordPress (without a plugin)

by: Rich Hauck

I wanted to add a fancyBox popup effect to any image that was embedded into the content area of a WordPress¬†post. I didn’t want to use a plugin for such a simple thing, and didn’t want to have to assign a CSS selector class every time I embedded an image. ¬†I found some add_filter() scripts online, but they had a tendency to overwrite some of the fields set in the admin’s media window. Rather than adding a filter in functions.php, I found a relatively elegant workaround that relies on some simple JQuery and CSS:

  1. Download and install fancyBox in your theme folder.
  2. In your header.php template file, add the following PHP code in your <head>:
    wp_enqueue_script('jquery.fancybox.js', '/wp-content/themes/sinvin/js/fancybox/jquery.fancybox.js');
    Calling this WP method instead of hardcoding the <script> tag lets WordPress manage conflicts. Note that the JQuery build that ships with WordPress should be loaded before this call.
  3. In your JQuery document.ready() call, add:
    $('a[href$="jpg"], a[href$="png"], a[href$="jpeg"]').fancybox();
    You can, of course, specify the selectors further, otherwise, this will target any hyperlink in your site that links directly to a JPG, PNG, or JPEG image file.
  4. Lastly, for this to work, the uploaded image must link to a larger version of itself. As of WordPress 3.4, it seems that uploaded images automatically link to a page with the media embedded. To change this, go to and find the field labeled “image_default_link_type”. This field may be empty or contain “post”, but you want to change it to “file”. Scroll to the bottom and save.

The end result should render a fancyBox displaying an image file any time you click on an image that’s linked to another image file.

2 thoughts on “Adding fancyBox to WordPress (without a plugin)

  1. Monti says:

    Thanks! Easy to use and no need for plugins)

  2. Erik Meyer says:

    I am completing my first theme and followed these steps, everything is working correctly however, I would like to add some facebook/twitter functionality to it. So, when a viewer comes into the website, they can click on the image and if they like the image and want to share the link they can use whatever social media they would like?

    I am confused by the exact coding and where to place it, so any help would be appreciated.

Leave a Reply

Your email address will not be published. Required fields are marked *

About Rich Hauck

Rich Hauck

I'm a creative technologist at Hauck Interactive, Inc. and an adjunct instructor at HACC. I live in Harrisburg, Pa. with my wife and three boys. I enjoy good coffee, Trappist beers, Orioles baseball, and good design.