GLightboxの導入方法

Filed under: functions.php,JavaScript — kdcs @ 25年9月21日 日曜日

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;
}

WordPressの投稿編集画面でadvanced custom fieldsで連続した複数画像フィールドをdivで囲むjs

Filed under: css,functions.php,JavaScript — kdcs @ 25年8月30日 土曜日

acfで画像フィールドを多く使うと縦長になってしまうので、3枚ずつを横並びにする方法。
初めはflort:leftで並べたが、画像が全部埋まらないとレイアウトが崩れてしまう。
これら複数の画像フィールドをdivで囲んでflexboxで処理する方法。

※注意点は、advanced custom fieldsの仕様が変わると修正しなければならない可能性がある
※acf proを使えばこの方法は必要ない

javascript( custom-admin-acf_img.js )

// acfの「複数画像フィールド」をdivで囲む ----------------------------
jQuery(function($) {
  const fieldGroups = [
    { prefix: 'banquet_img', wrapperClass: 'img_wrapper_banquet' },
    { prefix: 'room_img', wrapperClass: 'img_wrapper_rooms' }
  ];

fieldGroups.forEach(group => {
  const $fields = $(`[data-name^="${group.prefix}"]`);
    if ($fields.length) {
      const $wrapper = $(`<div class="${group.wrapperClass}"></div>`);
    
    // 先に wrapper を挿入
      $fields.first().before($wrapper);
    
    // その後 wrapper にフィールドを append
      $fields.each(function() {
        $wrapper.append($(this));
      });
    }
  });
});

※先にwrapperのdivを挿入してから画像フィールドを中に入れるという順にしないとエラーになる

functions.php

// あらかじめjsフォルダ内にcustom-admin-acf_img.jsを作成しておく----------------------------
function custom_admin_scripts() {
    $screen = get_current_screen();
    if ($screen->post_type !== 'page') {
        wp_enqueue_script('custom-admin-acf_imgjs', get_template_directory_uri() . '/js/custom-admin-acf_img.js');
    }
}
add_action('admin_enqueue_scripts', 'custom_admin_scripts');

css ( custom-admin-acf.css )

/* 画像(floatで3列にする) */
div.img_wrapper_rooms,
div.img_wrapper_banquet {
  display: flex;
  flex-wrap: wrap;
}
div.acf-field-image {
  width: calc(100% / 3) !important;
  padding: 16px;
}


/* div.acf-field-imageにflexが使えない場合 */
/*
min-height: 320px !important;
float: left !important;
clear: initial !important;
*/

advanced custom fields入力フィールドの幅を調整するcss(全投稿タイプの投稿編集画面対象)

Filed under: css,functions.php — kdcs @ 25年8月30日 土曜日

以前、特定のカスタム投稿タイプの編集画面にあるacf入力フィールドについてcssを適用する方法(こちら)を書いたが、今回は全投稿タイプの投稿編集画面対象。

あらかじめcssフォルダ内に「custom-admin-acf.css」を作成しておく
※こちらの記述では固定ページ、投稿ページ共にcustom-admin-acf-cssが出力される
copilot

function custom_admin_styles() {
    $screen = get_current_screen();
    if ($screen->base === 'post') {
        wp_enqueue_style('custom-admin-acf-css', get_template_directory_uri() . '/css/custom-admin-acf.css');
    }
}
add_action('admin_enqueue_scripts', 'custom_admin_styles');

「投稿編集画面だけ」に限定したいので、get_current_screen() を使って画面の種類を判定

固定ページを除外したい場合
※こちらの記述では投稿ページのみcustom-admin-acf-cssが出力される

function custom_admin_styles() {
    $screen = get_current_screen();
    if ($screen->post_type !== 'page') {
        wp_enqueue_style('custom-admin-acf-css', get_template_directory_uri() . '/css/custom-admin-acf.css');
    }
}
add_action('admin_enqueue_scripts', 'custom_admin_styles');

custom-admin-acf.cssの記述
入力フィールドのdata-nameにフィールド名が入っているのでそれぞれ入力し、widthを!important指定する

/* inputの場合 */
div[data-name="フィールド名"] input {
width: 300px !important;
}
/* selectの場合 */
div[data-name="フィールド名"] select {
width: 300px !important;
}

WordPressで管理画面の投稿一覧にACFでセットした画像の「あり・なし」を表示させる方法

Filed under: functions.php — kdcs @ 25年8月8日 金曜日

投稿やカスタム投稿でAdvanced Custom Fieldsを使って画像をアップロードしてページに掲載する場合、画像の設定が必須でないときは画像があったり無かったりするので投稿一覧でその「あり・なし」が分かるようにしたい。

functions.phpに記述
例はrestaurant_menuというカスタム投稿タイプでACFの画像フィールド名はrestaurant_menu_image

[php]
// カラムを追加
add_filter(‘manage_restaurant_menu_posts_columns’, ‘add_menu_image_column’);
function add_menu_image_column($columns) {
$columns[‘menu_image’] = ‘画像あり’;
return $columns;
}

// カラムの内容を表示
add_action(‘manage_restaurant_menu_posts_custom_column’, ‘show_menu_image_column’, 10, 2);
function show_menu_image_column($column, $post_id) {
if ($column === ‘menu_image’) {
$image = get_field(‘menu_image’, $post_id); // ACFの画像フィールド名
if ($image) {
echo ‘画像あり’;
} else {
echo ‘画像なし’;
}
}
}

]/php]

【未検証】(実際は’menu_image’もACFの画像フィールド名と同じ’restaurant_menu_image’にして実装した)
たぶん、一覧にカラムを追加するときにカラム名を’menu_image’にする場合は、項目の並べ替えの時にも’menu_image’を使う。

一覧にサムネイル画像を表示させる場合
(続きを読む…)

カスタム投稿タイプの編集でadvanced custom fields入力フィールドの幅を調整するcss

Filed under: css,functions.php — kdcs @ 25年5月15日 木曜日

WordPressでadvanced custom fieldsを使う場合、投稿編集画面に表示される入力フィールドの幅が100%指定で見た目が悪い。
この入力フィールドの幅をcssでカスタマイズする方法。

advanced custom fieldsのバージョンは6.3
カスタマイズ用のcssファイルを作成し、functions.phpで特定の投稿ポストの編集時に読み込ませるcssを指定する。

以下は特定のカスタム投稿タイプ用にcssフォルダ内にadmin-style.cssを作成し「your_custom_post_type」にカスタム投稿タイプを指定としている。
functions.php

function custom_admin_styles() {
    global $post_type;
    if ($post_type === 'your_custom_post_type') { // カスタム投稿タイプを指定
        wp_enqueue_style('custom-admin-css', get_template_directory_uri() . '/css/admin-style.css');
    }
}
add_action('admin_enqueue_scripts', 'custom_admin_styles');

admin-style.cssの記述
入力フィールドのdata-nameにフィールド名が入っているのでそれぞれ入力し、widthを!important指定する

/* inputの場合 */
div[data-name="フィールド名"] input {
  width: 300px !important;
}
/* selectの場合 */
div[data-name="フィールド名"] select {
  width: 300px !important;
}

cssファイルを作らずにfunctions.phpだけで行う方法

function custom_admin_css() {
    global $post_type;
    if ($post_type === 'your_custom_post_type') {
        echo '<style>
            #poststuff .acf-field { background-color: #f9f9f9; padding: 10px; }
            #post-body-content { max-width: 800px; }
        </style>';
    }
}
add_action('admin_head', 'custom_admin_css');

(続きを読む…)

サイト内検索

カテゴリー

最近の投稿

↑上に戻る