👏
WordPress × Smart Custom FieldsでGoogle Mapを表示する方法【SCF × iframe】
この記事について
WordPressでカスタムフィールドに登録した住所を使って、Googleマップを表示する方法を紹介します。
Smart Custom Fields(SCF)を利用し、繰り返しフィールドにも対応できるようにしています。
使用環境・前提
- WordPress
- Smart Custom Fields プラグイン
- 繰り返しフィールド(例:
salon-archive
)で複数店舗情報を持っている想定
<div class="flex__item">
<?php
$contents = SCF::get('salon-archive');
if (!empty($contents)) {
foreach ($contents as $content) {
$google_map_url = "https://www.google.com/maps?q=" . urlencode($salonAddress) . "&output=embed";
?>
<div class="map__container">
<?php if (!empty($salonAddress)) : ?>
<iframe
src="<?php echo esc_url($google_map_url); ?>"
width="100%" height="400" style="border:0;"
allowfullscreen loading="lazy"
referrerpolicy="no-referrer-when-downgrade">
</iframe>
<?php else : ?>
<p>住所が登録されていません</p>
<?php endif; ?>
</div>
</a>
<?php
}
}
?>
</div>
解説ポイント
-
$contents = SCF::get('salon-archive');
SCFで繰り返しフィールドの中身を取得 -
$salonAddress = $content['salon_address'];
各店舗の住所を変数に格納(←この行がないとエラーになる) -
urlencode()
を使ってGoogle Map用のURLにエンコード -
iframe
を使って地図を埋め込み -
empty()
チェックで住所が未入力の場合の分岐あり
注意点
-
salon_address
のキー名はSCFで設定したフィールド名に合わせてください。 - Google Mapの表示にはインターネット接続が必要です。
-
iframe
のスタイルはお好みで調整可能です。
おすすめカスタマイズ
- マーカー付きのGoogle Maps APIを使えば、より詳細な地図表示が可能になります。
終わりに
Smart Custom Fieldsを使えば、複数店舗の住所を簡単に管理し、柔軟に地図表示できます。
小規模な店舗サイトやサロンページに特におすすめの方法です。
Discussion