WordPress Snippet
Last active
August 5, 2022 15:00
-
-
Save ControlledChaos/0f91329cafff8d778cd0b176a7a6abbb to your computer and use it in GitHub Desktop.
Add data attributes to WordPress image links for use with Fancybox.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ); | |
?> |
Thanks! Just filled my needs.
This got me to where I needed to go too. Thank you!
Thanks a lot man.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi
im using this function and its very very very useful for installing fancybox in wp themes .
very thanks my friend.