jQueryに依存しないlightbox「GLightbox」をWordPressに導入する方法
GLightboxのダウンロード先はこちら
ダウンロード後に解凍。必要なファイルはdistフォルダ内「glightbox.min.cssとglightbox.min.js」
オプション設定はcommon.js内で行う。
cdnでGLightboxのCSSとJSをテーマに読み込ませる
functions.php
function mytheme_enqueue_scripts() {
// GLightboxのCSS
wp_enqueue_style('glightbox-css', 'https://cdn.jsdelivr.net/npm/glightbox/dist/css/glightbox.min.css');
// GLightboxのJS
wp_enqueue_script('glightbox-js', 'https://cdn.jsdelivr.net/npm/glightbox/dist/js/glightbox.min.js', array(), null, true);
// 初期化スクリプト
wp_add_inline_script('glightbox-js', 'const lightbox = GLightbox({ selector: ".glightbox" });');
}
add_action('wp_enqueue_scripts', 'mytheme_enqueue_scripts');
オプション設定
common.js
const lightbox = GLightbox({
selector: '.glightbox',
touchNavigation: true,
loop: true,
zoomable: false,
});
画像のaタグに class=”glightbox” を自動で追加する
functions.php
function add_glightbox_class_to_image_links($content) {
// aタグのhrefが画像ファイルの場合にclass="glightbox"を追加
$content = preg_replace_callback(
'/<a\s+([^>]*href=["\']([^"\']+\.(jpg|jpeg|png|gif|webp))["\'][^>]*)>/i',
function($matches) {
$tag = $matches[0];
// すでにclass属性があるか確認
if (strpos($tag, 'class=') !== false) {
// class属性にglightboxを追加
$tag = preg_replace('/class=["\']([^"\']*)["\']/', 'class="$1 glightbox"', $tag);
} else {
// class属性がない場合は追加
$tag = str_replace($matches[0], '<a ' . $matches[1] . ' class="glightbox">', $tag);
}
return $tag;
},
$content
);
return $content;
}
add_filter('the_content', 'add_glightbox_class_to_image_links');
※画像ファイルの形式を「jpg|jpeg|png|gif|webp」にしているのでpdfファイルは除外される
デフォルトの投稿タイプpostの記事だけに適用する記述
function add_glightbox_class_to_image_links($content) {
// デフォルト投稿タイプの個別ページのみ適用
if (is_singular('post') && is_main_query() && in_the_loop()) {
$content = preg_replace_callback(
'/<a\s+([^>]*href=["\']([^"\']+\.(jpg|jpeg|png|gif|webp))["\'][^>]*)>/i',
function($matches) {
$tag = $matches[0];
if (strpos($tag, 'class=') !== false) {
$tag = preg_replace('/class=["\']([^"\']*)["\']/', 'class="$1 glightbox"', $tag);
} else {
$tag = str_replace($matches[0], '<a ' . $matches[1] . ' class="glightbox">', $tag);
}
return $tag;
},
$content
);
}
return $content;
}
add_filter('the_content', 'add_glightbox_class_to_image_links');
・is_singular(‘post’):通常の投稿だけに限定
・is_main_query():メインクエリ(本文表示)だけに限定
・in_the_loop():WordPressループ内だけに限定
これで、固定ページやカスタム投稿、ウィジェットなどには影響せず、通常の投稿記事だけに glightbox クラスが追加されるようになる。
lightbox機能の速度はcssのanimationで行っている。
以下、アニメーションスピードのカスタマイズ
/*------------------------------------------------
GLightbox css custom animation
--------------------------------------------------*/
.gfadeIn {
-webkit-animation: gfadeIn 0.5s ease;
animation: gfadeIn 0.5s ease !important;
}
.gfadeOut {
-webkit-animation: gfadeOut 0.5s ease;
animation: gfadeOut 0.8s ease !important;
}
.gzoomIn {
-webkit-animation: gzoomIn 0.5s ease;
animation: gzoomIn 0.5s ease !important;
}
.gzoomOut {
-webkit-animation: gzoomOut 0.8s ease;
animation: gzoomOut 0.8s ease !important;
}