Tuesday, August 28, 2012

How to automatically add rel=”lightbox” to all images embedded in a post

The well known jQuery plugin Lightbox is a very simple way to open images in fancy full-screen boxes. It is very easy to use, but you have to add a rel=”lightbox” attribute to each image you want to open in a lightbox. Here’s a cool code snippet to automatically add the rel=”lightbox” attribute to all images embedded in your posts.
 
Paste the following code snippet in your functions.php file. 
Once done, a rel="lightbox" attribute will be automatically 
added to all images embedded in a post.
 
 function my_addlightboxrel($content) {   
      global $post;
      $pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";         
  $replacement = '<a$1href=$2$3.$4$5 rel="lightbox" 
                title="'.$post->post_title.'"$6>';        
  $content = preg_replace($pattern, $replacement, $content);       
  return $content;
  }
add_filter('the_content', 'my_addlightboxrel');

No comments:

Post a Comment