ControlledChaos of Controlled Chaos Design
7/20/2017 - 4:33 PM

Add data attributes to WordPress image links for use with Fancybox.

Add data attributes to WordPress image links for use with Fancybox.

<?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' );

?>

Fancybox Data Attributes to Images & Galleries

WordPress Snippet