LoginSignup
4
4

OGP画像を動的に変更させる

Last updated at Posted at 2020-10-02

ページをシェアする時にOGP画像を変更させたいという要望があったので、やってみました!

実装方法

動的に変更させたいページの url にパラメーター付きでアクセスした場合にOGP画像を変更させます。
といっても、head 要素内の og:urlog:imagecontent の値を変更させるだけです…

  1. パラメーター付きの url にアクセス
  2. url のパラメーターの値を取得
  3. head 要素内の og:urlog:imagecontent の値に url のパラメーターを挿入

パラメーターなしの url にアクセスした場合

<!-- https://example/にアクセス -->
<meta property="og:url" content="https://example/">
<meta property="og:image" content="https://example/og-image.png">

パラメーター付きの url にアクセスした場合

<!-- https://example/?image=hogeにアクセス -->
<meta property="og:url" content="https://example/?image=hoge">
<meta property="og:image" content="https://example/og-image_hoge.png">

実装

最初は JavaScript で実装したのですが、Facebookシェアデバッガーで確認したところ変更せず…
次に PHP で実装してみたところ、変更されたOGP画像が表示されました!

HTML
<!DOCTYPE html>
<html lang="ja">
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# website: http://ogp.me/ns/website#">
  <meta charset="utf-8">
  <title>タイトル</title>
  <meta name="viewport" content="width=device-width, viewport-fit=cover">
  <meta name="description" content="ディスクリプション">
  <meta name="twitter:card" content="summary_large_image">
  <meta property="og:title" content="タイトル">
  <meta property="og:description" content="ディスクリプション">
  <?php if (isset($_GET['image'])) : ?>
    <?php $imageParam = $_GET['image']; ?>
    <meta property="og:url" content="https://example/?param=<?php echo $imageParam; ?>">
    <meta property="og:image" content="https://example/og-image_<?php echo $imageParam; ?>.png">
  <?php else : ?>
    <meta property="og:url" content="https://example/">
    <meta property="og:image" content="https://example/og-image.png">
  <?php endif; ?>
</head>

補足

.html のまま PHP が動作するようにするためには .htaccess に設定が必要です。

.htaccess は、Apache Webサーバーで使用される設定ファイルの一種です。
ディレクトリ内に配置され、そのディレクトリおよびそのサブディレクトリに対する設定をカスタマイズするために使用されます。

AddType を使う方法

.htaccess
<FilesMatch "\.html$">
  AddType application/x-httpd-php .html
</FilesMatch>

AddHandler を使う方法

.htaccess
<FilesMatch "\.html$">
  # PHPのバージョンはご利用のバージョンに変更してください
  AddHandler php7-script .php
  # PHP 8 の場合は php8-script ではなく php-script となる
  AddHandler php-script .php
</FilesMatch>
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4