How can I integrate Fancybox 3 in Wordpress properly
I would like to integrate Facybox 3 in my WordPress (only on posts). It works but I'm a bit bothered cuz the initialize script is loaded after the core minified fancybox js
. So, here is the code I added in my child functions.php
:
// ENQUEUE FANCYBOX SCRIPT
function fancy_scripts() {
if ( is_single() ) {
wp_enqueue_script( 'fancybox-script', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js', array(), '3.3.5', true );
}
}
add_action( 'wp_enqueue_scripts', 'fancy_scripts' );
// INITIALIZE
function fancy_init(){
if ( is_single() ) {
?
script
jQuery(document).ready(function($){
$("[data-fancybox]").fancybox({
buttons: [
'zoom',
'fullScreen',
'share',
'thumbs',
'close'
],
protect: true
});
$(document).on('click', '.fancybox-share a.fancybox-share__button', function(e){
e.preventDefault();
var url = $(this).attr('href');
window.open(url, '_blank');
});
});
/script
?php
}
}
add_action('wp_footer','fancy_init')
;
// ENQUEUE CSS TO FOOTER
function fancy_footer_styles() {
if ( is_single() ) {
wp_enqueue_style( 'fancybox-style','https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.css' );
}
};
add_action( 'get_footer', 'fancy_footer_styles' );
And here is the output html
!--FOOTER--
script
jQuery(document).ready(function($){
$("[data-fancybox]").fancybox({
buttons: [
'zoom',
'fullScreen',
'share',
'thumbs',
'close'
],
protect: true
});
$(document).on('click', '.fancybox-share a.fancybox-share__button', function(e){
e.preventDefault();
var url = $(this).attr('href');
window.open(url, '_blank');
});
});
/script
link rel='stylesheet' id='fancybox-style-css' href='https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.css?ver=81a38b5eb2a4df901367646a93448a94' type='text/css' media='all' /
script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js?ver=3.3.5'/script
My questions are:
- Is it a problem that Initialize loads before the core fancy js?
- Is it a proper way to do that or do I absolutely have to put the initialize script in a separate js file and then enqueue it in the same function where I load the core file? As this, I mean :
.
function fancy_scripts() {
if ( is_single() ) {
wp_enqueue_script( 'fancybox-script', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js', array(), '3.3.5', true );
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom-scripts.js', array( 'jquery' ), true );
}
}
add_action( 'wp_enqueue_scripts', 'fancy_scripts' );
Topic lightbox wp-enqueue-script Wordpress
Category Web