勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

WordPressで自動でmetaタグのkeywordsとdescriptionを表示

   2024/05/22  WordPress

metaタグのkeywordsとdescriptionにて、基本的にはAll in One SEOとかで手動で設定していくべきなんだろうけど、記事数勝負のコンテンツとか自動生成系のコンテンツだとどうにもならないので、自動で表示する方法をメモ。

 

ソースコード

PC側テーマのヘッダー部分に下記ソースを記述。

<!--description&keywords-->
<meta name="description" content="<?php
if(is_home()){ ?>トップページに表示したいdescriptionを書く<?php }
elseif (is_single()){
$content_summary = strip_tags($post->post_content);
$content_summary = ereg_replace("(\r\n|\r|\n)", "", $content_summary);
$content_summary = mb_substr($content_summary, 0, 60). "...";
$content_summary=strip_tags($content_summary);
echo $content_summary; }
else { ?><?php bloginfo('description'); ?><?php } ?>">

<meta name="keywords" content="<?php
if(is_home()) { ?>トップページに設定したいキーワード,キーワード①,キーワード②<?php }
elseif (is_single()){ ?><?php $posttags = get_the_tags();if ($posttags) {foreach($posttags as $tag) {echo $tag->name . ','; }} ?><?php the_title(); ?><?php }
else {?>デフォルトのキーワード①,デフォルトのキーワード②<?php } ?>">
<!--description&keywords-->

あとは必要に応じて以下で修正する。

$content_summary = ereg_replace("\"", "", $content_summary);

 

参考サイト

http://on-ze.com/archives/817

 - WordPress

  関連記事

WordPressと別プログラム間でSESSIONが引き継げない場合の対応方法

同一サーバ内に自作したプログラムとWordPressを設置しており両者でセッショ ...

WordPressでカスタムフィールドとCSVファイル投稿する方法

WordPressでカスタムフィールド設定している環境に、CSVファイルアップロ ...

WordPressで複数のカテゴリーを取得する方法(get_the_category_list)

WordPressで1つの記事に対して複数カテゴリを設定していた場合、テーマによ ...

WordPressにてAdvanced Custom Fieldsを用いて連載(シリーズ)記事機能を実装する方法

先日「Series」プラグインで連載(シリーズ)記事機能の実装方法をメモしたが、 ...

WPのget_the_contentsでpタグが挿入されない場合の対応方法

WordPressのテーマを編集した際に表示が崩れるという症状が発生した。編集内 ...