記事ごとのメタディスクリプションやOGPを自動設定する方法

WordPressでブログを書いていると、投稿ごとにメタディスクリプションやOGP(Open Graph Protocol)を設定したいと思うことがあります。毎回手動で入力するのは手間ですが、PHPを使えば自動で生成できます。この記事では、functions.phpにコードを追加して自動設定する方法を紹介します。

投稿・固定ページに自動でメタディスクリプションとOGPタグを追加

上記の自動生成コードに加え、投稿編集画面にサイドボックスを追加することで、記事ごとのメタディスクリプションやOGP情報を管理画面で確認・編集できます。functions.phpに以下のコードを追加してください。


// 投稿・固定ページに自動でメタディスクリプションとOGPタグを追加
add_action('add_meta_boxes', function() {
    add_meta_box(
        'auto_meta_info',
        'メタ情報(自動生成&編集可能)',
        'show_auto_meta_info',
        ['post', 'page'], // 投稿と固定ページ両方対応
        'side',
        'high'
    );
});

function show_auto_meta_info($post) {
    // 保存済みメタ情報を取得
    $meta_description = get_post_meta($post->ID, '_meta_description', true);
    $og_title = get_post_meta($post->ID, '_og_title', true);
    $og_image = get_post_meta($post->ID, '_og_image', true);

    // 未設定の場合は自動生成
    if (!$meta_description) {
        $meta_description = mb_substr(strip_tags($post->post_content), 0, 120);
    }
    if (!$og_title) {
        $og_title = get_the_title($post->ID);
    }
    if (!$og_image) {
        $og_image = has_post_thumbnail($post->ID)
            ? get_the_post_thumbnail_url($post->ID, 'full')
            : get_stylesheet_directory_uri() . '/images/default-ogp.jpg';
    }

    echo '<p><label>メタディスクリプション:</label><br>';
    echo '<textarea style="width:100%;" name="meta_description">' . esc_textarea($meta_description) . '</textarea></p>';

    echo '<p><label>OGPタイトル:</label><br>';
    echo '<input type="text" style="width:100%;" name="og_title" value="' . esc_attr($og_title) . '"></p>';

    echo '<p><label>OGP画像 URL:</label><br>';
    echo '<input type="text" style="width:100%;" name="og_image" value="' . esc_attr($og_image) . '"></p>';
}

// 投稿保存時にメタ情報を保存
add_action('save_post', function($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    if (isset($_POST['meta_description'])) {
        update_post_meta($post_id, '_meta_description', sanitize_text_field($_POST['meta_description']));
    }
    if (isset($_POST['og_title'])) {
        update_post_meta($post_id, '_og_title', sanitize_text_field($_POST['og_title']));
    }
    if (isset($_POST['og_image'])) {
        update_post_meta($post_id, '_og_image', esc_url_raw($_POST['og_image']));
    }
});

// <head> に出力
add_action('wp_head', function() {
    if (!is_singular()) return; // 個別ページのみ
    global $post;

    $meta_description = get_post_meta($post->ID, '_meta_description', true);
    if (!$meta_description) {
        $meta_description = mb_substr(strip_tags($post->post_content), 0, 120);
    }

    $og_title = get_post_meta($post->ID, '_og_title', true);
    if (!$og_title) $og_title = get_the_title($post->ID);

    $og_image = get_post_meta($post->ID, '_og_image', true);
    if (!$og_image) {
        $og_image = has_post_thumbnail($post->ID)
            ? get_the_post_thumbnail_url($post->ID, 'full')
            : get_stylesheet_directory_uri() . '/images/default-ogp.jpg';
    }

    $og_url = get_permalink($post->ID);

    echo '<meta name="description" content="' . esc_attr($meta_description) . '">';
    echo '<meta property="og:title" content="' . esc_attr($og_title) . '">';
    echo '<meta property="og:description" content="' . esc_attr($meta_description) . '">';
    echo '<meta property="og:type" content="article">';
    echo '<meta property="og:url" content="' . esc_url($og_url) . '">';
    echo '<meta property="og:image" content="' . esc_url($og_image) . '">';
});
補足:
- is_singular() は投稿・固定ページの個別ページを対象にします。
- mb_substr() で説明文を120文字に制限しています。必要に応じて変更可能です。
- アイキャッチ画像がない場合は /images/default-ogp.jpg を使用します。
- SEOプラグインを使っている場合、タグの重複に注意してください。

子テーマのディレクトリ構造

  • child-theme/
    • style.css
    • functions.php
    • footer.php
    • header.php
    • js/
      • custom.js
    • images/
      • default-ogp.jpg