カスタムフィールドcustom_desを作成後、functions.phpに以下を記述
仕様:
カスタムフィールドから取得、ない場合は記事本文から抜粋を取得、それもない場合は記事の冒頭100文字抜粋を取得
// meta description function get_meta_description() { global $post; $description = ""; if ( is_home() ) { // ホームでは、ブログの説明文を取得 $description = get_bloginfo( 'description' ); } elseif ( is_category() ) { // カテゴリーページでは、カテゴリーの説明文を取得 $description = strip_tags(category_description()); } elseif ( is_single() || is_page() || is_tax() || is_archive() ) { // カスタムフィールドから取得 $custom_des = get_post_meta($post->ID,'custom_des',true); if (!empty($custom_des)) { $description = esc_html($custom_des); } else { if ($post->post_excerpt) { // 記事ページでは、記事本文から抜粋を取得 $description = $post->post_excerpt; } else { // post_excerpt で取れない時は、自力で記事の冒頭100文字を抜粋して取得 $description = strip_tags($post->post_content); $description = str_replace("\n", "", $description); $description = str_replace("\r", "", $description); $description = str_replace(array(" ", " "), "", $description); $description = mb_substr($description, 0, 100) . "..."; } } } else { ; } return $description; } // echo meta description tag function echo_meta_description_tag() { if ( is_home() || is_category() || is_single() || is_page() || is_tax() || is_archive() ) { echo '<meta name="description" content="' . get_meta_description() . '">' . "\n"; } } add_action('wp_head', 'echo_meta_description_tag');
コメント