【SEO】descriptionに本文の抜粋(–more–)を追加

SEO対策で、抜粋の description を記述したい時、

WordPress の header.php に以下を追加する。

<?php if ( is_single()): ?>
<?php if ($post->post_excerpt){ ?>
<meta name="description" content="<? echo $post->post_excerpt; ?>" />
<?php } else {
        $summary = $post->post_content;
        $summary = explode("<!--more-->", $summary)[0];
        $summary = strip_tags($summary);
        $summary = str_replace("\n", "", $summary);
        $summary = mb_substr($summary, 0, 120). "…"; ?>
<meta name="description" content="<?php echo $summary; ?>" />
<?php } ?>
<?php elseif ( is_home() || is_front_page() ): ?>
<meta name="description" content="<?php bloginfo('description'); ?>" />
<?php elseif ( is_category() ): ?>
<meta name="description" content="<?php echo category_description(); ?>" />
<?php elseif ( is_tag() ): ?>
<meta name="description" content="<?php echo tag_description(); ?>" />
<?php else: ?>
<meta name="description" content="<?php the_excerpt();?>" />
<?php endif; ?>

<!--more--> の抜粋にも対応している。