ASITIS

ブログ用のメモブログ

WordPressのbody_classに独自のclass名を追加

投稿ページにカテゴリースラッグが英語の場合追加
固定ページにページスラッグが英語の場合追加
固定ページで親ページがあれば親ページのスラッグも追加

 

以下をfunctions.phpに追加。

/*
 * body_classに独自のclass名を追加
 */
function add__body_class( $classes='' ) {
  global $page_id, $post;

  // 英語名のみ
  $check_eng = function( $prefix, $text ) {
    mb_regex_encoding( "Shift_jis" );
    if ( preg_match( "/^[a-zA-Z0-9-]+$/", $text ) ) {
      $classes[] = $prefix . '-' . $text;
    }
  };

  // 投稿ページでカテゴリースラッグを英語の場合追加
  if ( is_single() ) {
    foreach( ( get_the_category( $post->ID ) ) as $cat ) {
      $cat_slug = $cat->category_nicename;
      $check_eng( 'category', $cat_slug );
    }
  }
  // ページスラッグを英語の場合追加
  if (is_page()) {
    $page_slug = get_page( $page_id )->post_name;
    $check_eng( 'page', $page_slug );
  }
  // 親のページスラッグも英語の場合追加
  if ( isset( $post ) && $post->post_parent != 0 ) {
    $ancestors = array_reverse( get_post_ancestors( $post->ID ) );
    foreach( $ancestors as $ancestor ) {
      $ancestor = get_page( $ancestor );
      $ancestor_slug = $ancestor->post_name;
      $check_eng( 'page', $ancestor_slug );
    }
  }
  return $classes;
}
add_filter( 'body_class', 'add__body_class' );