以下のように表示される。
これにより、ランダムサムネイル用のIDを画像と合わせて、確認してコピーで取得できるようになる。

この設定は、ギャラリーブロックとPHP、CSSで構成されている。
コードスニペットにいれている。
// ギャラリー内の各画像の下にIDを「直接文字として」書き込み、末尾に一括コピー用エリアを追加
add_filter('render_block', 'add_id_and_bulk_copy_to_gallery', 10, 2);
function add_id_and_bulk_copy_to_gallery($block_content, $block) {
// ギャラリーブロックのみを対象にする
if ( $block['blockName'] === 'core/gallery' ) {
$ids = array();
// 1. 内包される画像ブロックからIDをすべて抽出
if ( !empty($block['innerBlocks']) ) {
foreach ( $block['innerBlocks'] as $inner_block ) {
if ( $inner_block['blockName'] === 'core/image' && isset($inner_block['attrs']['id']) ) {
$ids[] = $inner_block['attrs']['id'];
}
}
}
// 2. CSSに頼らず、HTMLの閉じタグ(</figure>)の直前にIDの文字を直接埋め込む
if ( !empty($ids) ) {
$index = 0;
// </figure> タグを見つけて、その直前に ID をテキストとして直接挿入する
$block_content = preg_replace_callback(
'/<\/figure>/i',
function($matches) use ($ids, &$index) {
$current_id = isset($ids[$index]) ? $ids[$index] : '';
$index++;
if ( $current_id ) {
// 画像の下に直接表示されるHTML(文字)を生成(真ん中寄せ、文字サイズ12px、グレー)
$id_html = '<div class="direct-img-id" style="text-align:center; font-size:12px; color:#666; font-weight:bold; margin-top:5px; margin-bottom:10px;">ID: ' . $current_id . '</div>';
return $id_html . '</figure>';
}
return $matches[0];
},
$block_content
);
// 3. カンマ区切りの文字列を作成し、ギャラリーの末尾にテキストエリアを追加
$comma_ids = implode(',', $ids);
$copy_html = '<div class="gallery-id-copy-box" style="clear:both;">';
$copy_html .= '<label class="gallery-id-copy-label"> ギャラリー画像ID一覧(コピー用)</label>';
$copy_html .= '<input type="text" value="' . esc_attr($comma_ids) . '" readonly onclick="this.select();" title="クリックして全選択">';
$copy_html .= '<span class="gallery-id-copy-note">※枠内をクリックすると全選択されるので、そのままコピー(Ctrl+C / ⌘+C)できます。</span>';
$copy_html .= '</div>';
// ギャラリーブロックの閉じタグの前に挿入
$block_content .= $copy_html;
}
}
return $block_content;
}コードスニペットにいれている。
/* ギャラリーや画像の下にIDを自動表示 */
/* 一括コピーエリアのデザイン */
.gallery-id-copy-box {
margin-top: 10px;
padding: 12px;
background-color: #f7f9fa;
border: 1px solid #ccd0d4;
border-radius: 4px;
width: 100%;
box-sizing: border-box;
clear: both; /* 回り込み解除 */
}
.gallery-id-copy-label {
display: block;
font-size: 13px;
font-weight: bold;
color: #333;
margin-bottom: 8px;
}
.gallery-id-copy-box input[type="text"] {
width: 100%;
padding: 8px 12px;
font-family: monospace; /* 数字を見やすく */
font-size: 14px;
color: #444;
background-color: #fff;
border: 1px solid #8c8f94;
border-radius: 4px;
cursor: pointer;
}
.gallery-id-copy-box input[type="text"]:focus {
border-color: #2271b1;
box-shadow: 0 0 0 1px #2271b1;
outline: 2px solid transparent;
}
.gallery-id-copy-note {
display: block;
font-size: 11px;
color: #666;
margin-top: 6px;
}
/* 画像の下のID表示の上下余白をギリギリまで詰める */
.direct-img-id {
margin-top: 2px !important; /* 画像と文字のすき間(デフォルト5pxから2pxへ) */
margin-bottom: 2px !important; /* 文字と下の要素のすき間(デフォルト10pxから2pxへ) */
}
