WordPressでPhotoSwipe対応のGoogleフォトを表示する方法

フォトエンベッドメーカー(Googleフォトで共有した画像やアルバムを記事へ埋め込むためのコード生成サービス)を使うとタイルギャラリーやスライダー形式の表示をブログに簡単に設置できます

生成されるコード (スライダーを除く) は、 Photo Swipe に対応したマークアップが行われているので、使用されているテーマで Photo Swipe(JavaScript&CSS)を読み込み有効化するとスマートフォン等でスワイプ操作を使って画像を閲覧出来るようになります

ご使用中のテーマに Photo Swipe を読み込む手順を紹介します

フォトエンベッドメーカー

フォトエンベッドメーカーの使い方については下記記事を参照してください

フォトエンベッドメーカー:Google フォトのWordPress埋込用コード生成
Googleフォトで共有した画像やアルバムをWordPressの記事へ埋め込むためのコードを生成するWebサービスです。アルバムを簡単にタイルギャラリーやスライダー等の形式で表示することが出来ます (^^)
フォトエンベッドメーカー:Google フォトのWordPress埋込用コード生成

Photo Swipe

PhotoSwipe

Photo Swipe は、スマートフォンで使われている様々なタッチジェスチャー( 前後画像へのフリック、ズームイン、拡大、ドラッグ、ズームアウト、クローズ等)をサポートするとても高機能で使い勝手の良く人気の JavaScript で記述されたギャラリーです

PhotoSwipe: Responsive JavaScript Image Gallery
Touch-friendly JavaScript image gallery for mobile and desktop, without dependencies. Responsive layout. Swipe and zoom gestures.
PhotoSwipe: Responsive JavaScript Image Gallery

テーマへの組み込み

Githubから Photo Swipe をダウンロードして使用中の WordPress テーマへ組み込みます

dimsemenov/PhotoSwipe
JavaScript image gallery for mobile and desktop, modular, framework independent – dimsemenov/PhotoSwipe
dimsemenov/PhotoSwipe

ダウンロードした最新版の Zip ファイルを解凍して、その中の dist フォルダーを使用中の WordPress テーマのフォルダー以下にFTP等を使ってコピーします

例えば、TwentySeventeen の子テーマ(仮にTwentySeventeen-child)を使っているとすると、解凍したファイルの dist フォルダーを子テーマのフォルダーにコピーします

次に、下記で紹介しているコードをコピーして photoswipe-init.js というファイル名で保存してください。保存したファイルを FTP等を使って先程コピーした dist フォルダーへ同様にコピーします

  1. /*
  2. * Photo Swipe
  3. * https://github.com/dimsemenov/photoswipe MIT license
  4. *
  5. * support markup pswp-gallery class under 'figure > a > img' or 'ul > li > figure > a > img'
  6. */
  7. const uihtml = '<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true"><div class="pswp__bg"></div><div class="pswp__scroll-wrap"><div class="pswp__container"><div class="pswp__item"></div><div class="pswp__item"></div><div class="pswp__item"></div></div><div class="pswp__ui pswp__ui--hidden"><div class="pswp__top-bar"><div class="pswp__counter"></div><button class="pswp__button pswp__button--close" title="Close (Esc)"></button><button class="pswp__button pswp__button--share" title="Share"></button><button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button><button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button><div class="pswp__preloader"><div class="pswp__preloader__icn"><div class="pswp__preloader__cut"><div class="pswp__preloader__donut"></div></div></div></div></div><div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap"><div class="pswp__share-tooltip"></div></div><button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button><button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button><div class="pswp__caption"><div class="pswp__caption__center"></div></div></div></div></div>';
  8.  
  9. var initPhotoSwipeFromDOM = function(gallerySelector) {
  10. // parse slide data (url, title, size ...) from DOM elements
  11. // (children of gallerySelector)
  12. var parseThumbnailElements = function(el) {
  13. var thumbElements = el.childNodes,
  14. numNodes = thumbElements.length,
  15. items = [],
  16. listItemEl,
  17. figureEl,
  18. linkEl,
  19. size,
  20. item;
  21.  
  22. for(var i = 0; i < numNodes; i++) {
  23.  
  24. listItemEl = thumbElements[i]; // <figure> or <li> element
  25.  
  26. // include only element nodes
  27. if(listItemEl.nodeType !== 1) {
  28. continue;
  29. }
  30. if(listItemEl.tagName && listItemEl.tagName.toUpperCase() === 'FIGURE')
  31. figureEl = listItemEl;
  32. else
  33. figureEl = listItemEl.children[0];
  34.  
  35. linkEl = figureEl.children[0]; // <a> element
  36.  
  37. size = linkEl.getAttribute('data-size').split('x');
  38.  
  39. // create slide object
  40. item = {
  41. src: linkEl.getAttribute('href'),
  42. w: parseInt(size[0], 10),
  43. h: parseInt(size[1], 10)
  44. };
  45.  
  46.  
  47. if(figureEl.children.length > 1) {
  48. // <figcaption> content
  49. item.title = figureEl.children[1].innerHTML;
  50. }
  51.  
  52. if(linkEl.children.length > 0) {
  53. // <img> thumbnail element, retrieving thumbnail url
  54. item.msrc = linkEl.children[0].getAttribute('src');
  55. }
  56.  
  57. item.el = figureEl; // save link to element for getThumbBoundsFn
  58. items.push(item);
  59. }
  60.  
  61. return items;
  62. };
  63.  
  64. // find nearest parent element
  65. var closest = function closest(el, fn) {
  66. return el && ( fn(el) ? el : closest(el.parentNode, fn) );
  67. };
  68.  
  69. // triggers when user clicks on thumbnail
  70. var onThumbnailsClick = function(e) {
  71. e = e || window.event;
  72. e.preventDefault ? e.preventDefault() : e.returnValue = false;
  73.  
  74. var eTarget = e.target || e.srcElement;
  75.  
  76. // find root element of slide
  77. var clickedListItem = closest(eTarget, function(el) {
  78. if(el.tagName && el.tagName.toUpperCase() === 'FIGURE'){
  79. if(el.parentElement.tagName.toUpperCase() === 'LI')
  80. return false; //skip
  81. else
  82. return true;
  83. } else if(el.tagName && el.tagName.toUpperCase() === 'LI'){
  84. if(el.children[0].tagName.toUpperCase() === 'FIGURE')
  85. return true;
  86. else
  87. return false;
  88. }
  89. return false;
  90. });
  91.  
  92. if(!clickedListItem) {
  93. return;
  94. }
  95.  
  96. // find index of clicked item by looping through all child nodes
  97. // alternatively, you may define index via data- attribute
  98. var clickedGallery = clickedListItem.parentNode,
  99. childNodes = clickedListItem.parentNode.childNodes,
  100. numChildNodes = childNodes.length,
  101. nodeIndex = 0,
  102. index;
  103.  
  104. for (var i = 0; i < numChildNodes; i++) {
  105. if(childNodes[i].nodeType !== 1) {
  106. continue;
  107. }
  108.  
  109. if(childNodes[i] === clickedListItem) {
  110. index = nodeIndex;
  111. break;
  112. }
  113. nodeIndex++;
  114. }
  115.  
  116.  
  117.  
  118. if(index >= 0) {
  119. // open PhotoSwipe if valid index found
  120. openPhotoSwipe( index, clickedGallery );
  121. }
  122. return false;
  123. };
  124.  
  125. // parse picture index and gallery index from URL (#&pid=1&gid=2)
  126. var photoswipeParseHash = function() {
  127. var hash = window.location.hash.substring(1),
  128. params = {};
  129.  
  130. if(hash.length < 5) {
  131. return params;
  132. }
  133.  
  134. var vars = hash.split('&');
  135. for (var i = 0; i < vars.length; i++) {
  136. if(!vars[i]) {
  137. continue;
  138. }
  139. var pair = vars[i].split('=');
  140. if(pair.length < 2) {
  141. continue;
  142. }
  143. params[pair[0]] = pair[1];
  144. }
  145.  
  146. if(params.gid) {
  147. params.gid = parseInt(params.gid, 10);
  148. }
  149.  
  150. return params;
  151. };
  152.  
  153. var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
  154. var pswpElement = document.querySelectorAll('.pswp')[0],
  155. gallery,
  156. options,
  157. items;
  158.  
  159. items = parseThumbnailElements(galleryElement);
  160.  
  161. // define options (if needed)
  162. options = {
  163.  
  164. // define gallery index (for URL)
  165. galleryUID: galleryElement.getAttribute('data-pswp-uid'),
  166. //add option settings
  167. shareEl: false,
  168.  
  169. getThumbBoundsFn: function(index) {
  170. // See Options -> getThumbBoundsFn section of documentation for more info
  171. var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
  172. pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
  173. rect = thumbnail.getBoundingClientRect();
  174.  
  175. return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
  176. }
  177.  
  178. };
  179.  
  180. // PhotoSwipe opened from URL
  181. if(fromURL) {
  182. if(options.galleryPIDs) {
  183. // parse real index when custom PIDs are used
  184. // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
  185. for(var j = 0; j < items.length; j++) {
  186. if(items[j].pid == index) {
  187. options.index = j;
  188. break;
  189. }
  190. }
  191. } else {
  192. // in URL indexes start from 1
  193. options.index = parseInt(index, 10) - 1;
  194. }
  195. } else {
  196. options.index = parseInt(index, 10);
  197. }
  198.  
  199. // exit if index not found
  200. if( isNaN(options.index) ) {
  201. return;
  202. }
  203.  
  204. if(disableAnimation) {
  205. options.showAnimationDuration = 0;
  206. }
  207.  
  208. // Pass data to PhotoSwipe and initialize it
  209. gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
  210. gallery.init();
  211. };
  212.  
  213. // loop through all gallery elements and bind events
  214. var galleryElements = document.querySelectorAll( gallerySelector );
  215.  
  216. for(var i = 0, l = galleryElements.length; i < l; i++) {
  217. galleryElements[i].setAttribute('data-pswp-uid', i+1);
  218. galleryElements[i].onclick = onThumbnailsClick;
  219. }
  220.  
  221. // Parse URL and open gallery if it contains #&pid=3&gid=1
  222. var hashData = photoswipeParseHash();
  223. if(hashData.pid && hashData.gid) {
  224. openPhotoSwipe( hashData.pid , galleryElements[ hashData.gid - 1 ], true, true );
  225. }
  226. };
  227.  
  228. window.addEventListener('DOMContentLoaded', function(){
  229. document.body.insertAdjacentHTML("beforeend", uihtml);
  230. initPhotoSwipeFromDOM(".pswp-gallery");
  231. });

この photoswipe-init.js は、PhotoSwipe Getting Started How to build an array of slides from a list of links のサンプルコードをカスタマイズして pswp-gallery クラス下の ‘figure > a > img‘ 及び ’ul > li > figure > a > img‘ でマークアップされているギャラリーへ対応させたものです

コピーしたファイルは、子テーマで以下のような感じにファイルが配置されているはずです

次にテーマの function.php に Photo Swipe を読み込むように以下のような記述を追加します

  1. // Photo Swipe (https://github.com/dimsemenov/photoswipe) の CSS/JavaScript 読み込み
  2. function photo_swipe_load(){
  3. $path = get_stylesheet_directory_uri() . '/dist';
  4. wp_enqueue_style( 'style-photoswipe', "{$path}/photoswipe.css" );
  5. wp_enqueue_style( 'style-photoswipe-skin', "{$path}/default-skin/default-skin.css" );
  6. wp_enqueue_script( 'photoswipe', "{$path}/photoswipe.min.js", array(), '', true);
  7. wp_enqueue_script( 'photoswipe-ui', "{$path}/photoswipe-ui-default.min.js", array(), '', true);
  8. wp_enqueue_script( 'photoswipe-init', "{$path}/photoswipe-init.js", array(), '', true);
  9. }
  10. add_action('wp_enqueue_scripts', 'photo_swipe_load');

以上で準備OKです

セルティス製 Celtis-Speedy テーマの Ver1.1.0 以降には Photo Swipe 機能が実装済です。Celtis-Speedy をご利用の場合は紹介しているテーマへの組み込みは不要です。

サンプル表示

後は、フォトエンベッドメーカーで Googleフォトの共有コードから埋め込み用コードを生成して記事にそのコードを貼り付けるだけで Photo Swipe に対応したギャラリー表示となります

下記はタイルギャラリーのサンプルです。画像をクリックして Photo Swipe による様々なタッチジェスチャーを試してみてください

フォトエンベッドメーカーに関するご意見や質問等はフォーラムへお願い致します

 

※フォーラムへ参加するには、無料の メンバー登録 が必要です

※参加する場合は 運用ルールと使い方 をお読みください

以上

WordPressへ埋め込んだ Googleフォトを Photo Swipe で表示させる方法について紹介いたしました


まとめ記事紹介

go-to-top