WordPressにおけるSEOメタタグと画像Alt属性の自動生成実装

Webサイトの検索エンジン最適化(SEO)を効率化するため、記事のメタ情報と画像属性を動的に生成する手法があります。標準的なSEOガイドラインでは、キーワードを3つから6つの範囲に設定し、説明文は約160文字(日本語の場合70〜80文字程度)に収めることが推奨されます。また、すべての画像には適切なAlt属性を設定することがアクセシビリティとSEOの両面で重要となります。

1. キーワードの動的生成

キーワードは、親カテゴリ、子カテゴリ、および記事タイトルを組み合わせて構成します。既存のタグを使用する代わりに、カテゴリ階層を活用して一貫性のあるメタデータを生成します。

以下のコードをテーマの functions.php に追加します。配列操作と implode を使用して、重複排除と文字列連結を効率的に行います。

/**
 * 動的にメタキーワードを生成して出力する
 */
function generate_auto_meta_keywords() {
    if ( ! is_single() ) {
        return;
    }

    global $post;
    $keyword_parts = [];

    // カテゴリ情報の取得
    $categories = get_the_category( $post->ID );
    if ( ! empty( $categories ) ) {
        $current_cat = $categories[0];

        // 親カテゴリ名の追加
        if ( $current_cat->category_parent ) {
            $parent_name = get_cat_name( $current_cat->category_parent );
            if ( $parent_name ) {
                $keyword_parts[] = $parent_name;
            }
        }

        // 現在のカテゴリ名の追加
        $keyword_parts[] = $current_cat->name;
    }

    // 記事タイトルの追加
    $title = get_the_title( $post->ID );
    if ( $title ) {
        $keyword_parts[] = $title;
    }

    // 重複を削除し、数を制限(3〜6個の範囲に調整可能)
    $unique_parts = array_unique( $keyword_parts );
    $limited_parts = array_slice( $unique_parts, 0, 6 );

    // カンマ区切りで連結
    $final_keywords = implode( ', ', $limited_parts );

    if ( $final_keywords ) {
        echo sprintf( '<meta name="keywords" content="%s">%s', esc_attr( $final_keywords ), "\n" );
    }
}

// wp_headアクションにフック
add_action( 'wp_head', 'generate_auto_meta_keywords' );

2. 説明文の自動抽出と文字数制御

記事の抜粋がない場合、本文の内容からHTMLタグや不要な空白を除去し、指定した文字数にトリミングして説明文を生成します。

/**
 * 動的にメタ説明文を生成して出力する
 */
function generate_auto_meta_description() {
    if ( ! is_singular() ) {
        return;
    }

    global $post;
    $raw_content = $post->post_content;

    // HTMLタグの除去
    $clean_text = wp_strip_all_tags( $raw_content );

    // 改行や空白文字の正規化
    $clean_text = preg_replace( '/\s+/', ' ', $clean_text );
    $clean_text = trim( $clean_text );

    // 文字数の制限(UTF-8対応で160文字程度に切り詰め)
    // 必要に応じて長さを調整
    $limited_length = 160;
    $final_description = mb_strimwidth( $clean_text, 0, $limited_length, '...' );

    if ( $final_description ) {
        echo sprintf( '<meta name="description" content="%s">%s', esc_attr( $final_description ), "\n" );
    }
}

// wp_headアクションにフック
add_action( 'wp_head', 'generate_auto_meta_description' );

3. 画像へのAlt属性自動付与

クライアントサイドのJavaScriptに依存せず、サーバーサイドでコンテンツを処理して画像タグにAlt属性を注入します。これにより、JavaScriptが無効な環境でも正しく属性が出力され、パフォーマンスの最適化にも寄与します。

以下のフィルターフックを functions.php に追加します。正規表現を使用して画像タグを検出し、Alt属性が存在しない場合に記事タイトルをベースに自動的に設定します。

/**
 * 記事内の画像タグにAlt属性を自動的に付与する
 */
function auto_inject_image_alt_attributes( $content ) {
    if ( is_single() && have_posts() ) {
        $post_title = get_the_title();
        
        // 画像タグの検索パターン
        // alt属性が既に存在するかをチェックするためのコールバックを使用
        $pattern = '/<img\s([^>]*)>/i';

        $content = preg_replace_callback( $pattern, function( $matches ) use ( $post_title ) {
            $img_tag = $matches[0];
            $attrs = $matches[1];

            // 既存のalt属性の有無を確認
            if ( ! preg_match( '/\balt\s*=\s*["\'][^"\']*["\']/', $attrs ) ) {
                // alt属性がない場合、記事タイトルをセット
                $new_attr = sprintf( 'alt="%s"', esc_attr( $post_title ) );
                return str_replace( '<img ', '<img ' . $new_attr . ' ', $img_tag );
            }
            
            return $img_tag;
        }, $content );
    }

    return $content;
}

// the_contentフィルターにフック
add_filter( 'the_content', 'auto_inject_image_alt_attributes' );

タグ: WordPress PHP seo the_content wp_head

8月18日 06:42 投稿