メタディスクリプションを設置する【functions.php】
クラシックエディタに抜粋を入れて、簡単にメタディスクリプションを設置できるようにしましょう。ホーム、カテゴリー、各記事に対応しています。
準備: Classic editor上の右上「表示オプション」で抜粋にチェックをいれること。
/* Meta description on home, singlepost and category */
function register_meta_description() {
global $post;
if ( is_singular() ) {
$post_description = strip_tags( $post->post_excerpt );
$post_description = mb_substr( $post_description, 0, 120, 'utf-8' );
echo '';
}
if( is_home() ) {
echo '';
}
if( is_category() ) {
$cat_description = strip_tags( category_description() );
echo '';
}
}
add_action( 'wp_head', 'register_meta_description' );
- strip_tags…文字列のみを残す
- mb_substr…マルチバイト対応、ディスクリプションに残す文字数を設定
- singlepost / home / category対応
参考: How to Add Meta Tags to WordPress Without Plugins – GretaThemes
global $post 参考: WP_Post | Class | WordPress Developer Resources