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:
- Download and install fancyBox in your theme folder.
- In your header.php template file, add the following PHP code in your <head>:
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.
- In your JQuery
$('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.
- 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 http://www.yoursite.com/wp-admin/options.php 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.