Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add data attributes to WordPress image links for use with Fancybox.

Fancybox Data Attributes to Images & Galleries

WordPress Snippet

<?php
/**
* Add data attributes for Fancybox
*/
// Gallery images
function ccd_fancybox_gallery_attribute( $content, $id ) {
// Restore title attribute
$title = get_the_title( $id );
return str_replace('<a', '<a data-type="image" data-fancybox="gallery" title="' . esc_attr( $title ) . '" ', $content);
}
add_filter( 'wp_get_attachment_link', 'ccd_fancybox_gallery_attribute', 10, 4 );
// Single images
function ccd_fancybox_image_attribute( $content ) {
global $post;
$pattern = "/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
$replace = '<a$1href=$2$3.$4$5 data-type="image" data-fancybox="image">';
$content = preg_replace( $pattern, $replace, $content );
return $content;
}
add_filter( 'the_content', 'ccd_fancybox_image_attribute' );
?>
@yawarir
Copy link

yawarir commented Feb 27, 2018

hi
im using this function and its very very very useful for installing fancybox in wp themes .
very thanks my friend.

@yduke
Copy link

yduke commented Aug 14, 2018

Thanks! Just filled my needs.

@royce002
Copy link

royce002 commented Jan 16, 2019

This got me to where I needed to go too. Thank you!

@jupa8712
Copy link

jupa8712 commented Apr 3, 2019

Thanks a lot man.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment