Skip to content

Instantly share code, notes, and snippets.

@ControlledChaos
Last active August 5, 2022 15:00
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ControlledChaos/0f91329cafff8d778cd0b176a7a6abbb to your computer and use it in GitHub Desktop.
Save ControlledChaos/0f91329cafff8d778cd0b176a7a6abbb to your computer and use it in GitHub Desktop.
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' );
?>
@yduke
Copy link

yduke commented Aug 14, 2018

Thanks! Just filled my needs.

@royce002
Copy link

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