WP descriptionの生成
WordPressサイトのDescriptionを生成する際のメモです。
私の場合 慣れてしまっているので、今どき珍しくSmartyのテンプレートを作成してWordPressのテーマを作っています。
一般的な書き方とは違うかもしれません。
※ 特にプラグインを要しません
PHPコード サンプル
head.phpに、以下の様なコードを追加して、metaタグを出力しています。
<?php $str = ""; $desc_len = 80; // $post->post_contentから取得する最大文字数を指定 //抜粋がある場合は、抜粋を取得 if(@$post->post_excerpt){ $str = $post->post_excerpt; }else{ // $post->post_contentを取得して、<>で囲まれた部分を除去 $str = strip_tags($post->post_content); // 改行や特殊文字を除去 $str = preg_replace("/\[[a-z,\/]*\]|\n|\r/", "", $str); // 先頭から(全角も1文字として)文字を指定した分だけ取得。末尾に「…」をつける。 if(strlen($str) > $desc_len){ $str = mb_substr($str, 0, $desc_len). "…"; } } if(!strlen($str)){ // 文字が取得できなかった場合、サイトに設定されたdescriptionを設定 $str = get_bloginfo("description"); } // metaタグ生成 $str = '<meta name="description" content="' . $str .'" />'; // 出力 echo $str; ?>
この様なコードを、is_page、is_single、$post->ID、$post->post_name、などで条件分岐してmetaタグを出力するようにしています。
※ 特にプラグインを要しません
