body_class()で出力されたcssにCV用のクラスを追加する

body_class()で出力されたcssにCV用のクラスを追加する

body_class()を用いているbodyに対して、カスタムフィールドで設定したクラスを追加する。
※カスタムフィールドはテキストで入力したい値を記載する。例ではkeyを「cv_num」とする。

■ クラス取得&判別用処理

<?php
    /* カスタムフィールドを(多次元)配列で取得 */
    $custom_fields = get_post_meta(get_the_ID(), '', false);
    /* カスタムフィールドのキー「body-class」の配列をクラスに追加 */
    if (isset($custom_fields['cv_num'])){
        $body_class = get_body_class($custom_fields['cv_num']);
    }else{
        $body_class = get_body_class();
    }
  ?>

■ 出力

<body class="<?php echo join(' ', $body_class); ?>">

————————–

■ クラスを除去したい場合の処理

<?php
if (isset($custom_fields['body-class-x'])) {
    $body_class_x = $custom_fields['body-class-x'];
    foreach ($body_class_x as $value) {
        $key = array_search($value, $body_class);
        if ($key !== false)
            unset($body_class[$key]);
    }
}
$body_class = array_values(array_unique($body_class));
?>

参考サイト

れいぶろぐ
【WordPress】body_class() のクラスを追加したり除去したりする
http://labe.wp.xdomain.jp/post/617